}
vfunc_paint(paintContext) {
- let framebuffer = paintContext.get_framebuffer();
- let coglContext = framebuffer.get_context();
- let alloc = this.get_allocation_box();
+ const framebuffer = paintContext.get_framebuffer();
+ const coglContext = framebuffer.get_context();
+ const alloc = this.get_allocation_box();
- let pipeline = Cogl.Pipeline.new(coglContext);
+ const pipeline = Cogl.Pipeline.new(coglContext);
pipeline.set_color4ub(255, 0, 0, 255);
framebuffer.draw_rectangle(pipeline,
All closures should be wrapped with Function.prototype.bind or use arrow
notation.
```javascript
- let closure1 = () => this._fnorbate();
- let closure2 = this._fnorbate.bind(this);
+ const closure1 = () => this._fnorbate();
+ const closure2 = this._fnorbate.bind(this);
```
A more realistic example would be connecting to a signal on a method of a
export class MyClass {
constructor() {
- let fnorb = new FnorbLib.Fnorb();
+ const fnorb = new FnorbLib.Fnorb();
fnorb.connect('frobate', this._onFnorbFrobate.bind(this));
}
```javascript
desaturateActor(actor, desaturate) {
- let factor = desaturate ? 1.0 : 0.0;
+ const factor = desaturate ? 1.0 : 0.0;
actor.ease_property('@effects.desaturate.factor', factor, {
duration: 500, // ms
mode: Clutter.AnimationMode.EASE_OUT_QUAD,
this._errorView.buffer.text = formattedError;
// markdown for pasting in gitlab issues
- let lines = [
+ const lines = [
`The settings of extension ${uuid} had an error:`,
'```',
formattedError.replace(/\n$/, ''), // remove trailing newline
}
_moveFocusToItems() {
- let hasItems = this.numItems > 0;
+ const hasItems = this.numItems > 0;
if (!hasItems)
return;
if (global.stage.get_key_focus() !== this)
return;
- let focusSet = this.navigate_focus(null, St.DirectionType.TAB_FORWARD, false);
+ const focusSet = this.navigate_focus(null, St.DirectionType.TAB_FORWARD, false);
if (!focusSet) {
const laters = global.compositor.get_laters();
laters.add(Meta.LaterType.BEFORE_REDRAW, () => {
}
scrollToItem(item) {
- let box = item.get_allocation_box();
+ const box = item.get_allocation_box();
const adjustment = this._scrollView.vadjustment;
- let value = (box.y1 + adjustment.step_increment / 2.0) - (adjustment.page_size / 2.0);
+ const value = (box.y1 + adjustment.step_increment / 2.0) - (adjustment.page_size / 2.0);
adjustment.ease(value, {
duration: SCROLL_ANIMATION_TIME,
mode: Clutter.AnimationMode.EASE_OUT_QUAD,
addItem(key, text) {
this.removeItem(key);
- let item = new AuthListItem(key, text);
+ const item = new AuthListItem(key, text);
this._box.add_child(item);
this._items.set(key, item);
if (!this._items.has(key))
return;
- let item = this._items.get(key);
+ const item = this._items.get(key);
item.destroy();
this._initInputRow();
- let capsLockPlaceholder = new St.Label();
+ const capsLockPlaceholder = new St.Label();
this.add_child(capsLockPlaceholder);
this._capsLockWarningLabel = new ShellEntry.CapsLockWarning({
});
this._mainBox.add_child(this._authList);
- let entryParams = {
+ const entryParams = {
style_class: 'login-dialog-prompt-entry',
can_focus: true,
x_expand: true,
});
entry.clutter_text.connect('activate', () => {
- let shouldSpin = entry === this._passwordEntry;
+ const shouldSpin = entry === this._passwordEntry;
if (entry.reactive)
this._activateNext(shouldSpin);
});
}
showTimedLoginIndicator(time) {
- let hold = new Batch.Hold();
+ const hold = new Batch.Hold();
this.hideTimedLoginIndicator();
!actor)
return;
- let oldActor = this._defaultButtonWellActor;
+ const oldActor = this._defaultButtonWellActor;
if (oldActor)
oldActor.remove_all_transitions();
setChoiceList(promptMessage, choiceList) {
this._authList.clear();
this._authList.label.text = promptMessage;
- for (let key in choiceList) {
- let text = choiceList[key];
+ for (const key in choiceList) {
+ const text = choiceList[key];
this._authList.addItem(key, text);
}
}
setUser(user) {
- let oldChild = this._userWell.get_child();
+ const oldChild = this._userWell.get_child();
if (oldChild)
oldChild.destroy();
- let userWidget = new UserWidget.UserWidget(user, Clutter.Orientation.VERTICAL);
+ const userWidget = new UserWidget.UserWidget(user, Clutter.Orientation.VERTICAL);
this._userWell.set_child(userWidget);
if (!user)
}
reset() {
- let oldStatus = this.verificationStatus;
+ const oldStatus = this.verificationStatus;
this.verificationStatus = AuthPromptStatus.NOT_VERIFYING;
this.cancelButton.reactive = this._hasCancelButton;
this.cancelButton.can_focus = this._hasCancelButton;
return;
}
- let signalId = this._userVerifier.connect('no-more-messages', () => {
+ const signalId = this._userVerifier.connect('no-more-messages', () => {
this._userVerifier.disconnect(signalId);
this._userVerifier.clear();
onComplete();
return;
this.acquire();
- let signalId = hold.connect('release', () => {
+ const signalId = hold.connect('release', () => {
hold.disconnect(signalId);
this.release();
});
export class ConcurrentBatch extends Batch {
process() {
- let hold = this.runTask();
+ const hold = this.runTask();
if (hold)
this.hold.acquireUntilAfter(hold);
export class ConsecutiveBatch extends Batch {
process() {
- let hold = this.runTask();
+ const hold = this.runTask();
if (hold && hold.isAcquired()) {
// This task is inhibiting the batch. Wait on it
// before processing the next one.
- let signalId = hold.connect('release', () => {
+ const signalId = hold.connect('release', () => {
hold.disconnect(signalId);
this.nextTask();
});
Signals: {'activate': {}},
}, class UserListItem extends St.Button {
_init(user) {
- let layout = new St.BoxLayout({
+ const layout = new St.BoxLayout({
orientation: Clutter.Orientation.VERTICAL,
x_expand: true,
});
}
showTimedLoginIndicator(time) {
- let hold = new Batch.Hold();
+ const hold = new Batch.Hold();
this.hideTimedLoginIndicator();
this._timedLoginIndicator.visible = true;
- let startTime = GLib.get_monotonic_time();
+ const startTime = GLib.get_monotonic_time();
this._timedLoginTimeoutId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 33,
() => {
- let currentTime = GLib.get_monotonic_time();
- let elapsedTime = (currentTime - startTime) / GLib.USEC_PER_SEC;
+ const currentTime = GLib.get_monotonic_time();
+ const elapsedTime = (currentTime - startTime) / GLib.USEC_PER_SEC;
this._timedLoginIndicator.scale_x = elapsedTime / time;
if (elapsedTime >= time) {
this._timedLoginTimeoutId = 0;
if (global.stage.get_key_focus() !== this)
return;
- let focusSet = this.navigate_focus(null, St.DirectionType.TAB_FORWARD, false);
+ const focusSet = this.navigate_focus(null, St.DirectionType.TAB_FORWARD, false);
if (!focusSet) {
const laters = global.compositor.get_laters();
laters.add(Meta.LaterType.BEFORE_REDRAW, () => {
}
scrollToItem(item) {
- let box = item.get_allocation_box();
+ const box = item.get_allocation_box();
const adjustment = this.vadjustment;
- let value = (box.y1 + adjustment.step_increment / 2.0) - (adjustment.page_size / 2.0);
+ const value = (box.y1 + adjustment.step_increment / 2.0) - (adjustment.page_size / 2.0);
adjustment.ease(value, {
mode: Clutter.AnimationMode.EASE_OUT_QUAD,
duration: _SCROLL_ANIMATION_TIME,
}
jumpToItem(item) {
- let box = item.get_allocation_box();
+ const box = item.get_allocation_box();
const adjustment = this.vadjustment;
- let value = (box.y1 + adjustment.step_increment / 2.0) - (adjustment.page_size / 2.0);
+ const value = (box.y1 + adjustment.step_increment / 2.0) - (adjustment.page_size / 2.0);
adjustment.set_value(value);
}
if (user.locked)
return;
- let userName = user.get_user_name();
+ const userName = user.get_user_name();
if (!userName)
return;
this.removeUser(user);
- let item = new UserListItem(user);
+ const item = new UserListItem(user);
this._box.add_child(item);
this._items.set(userName, item);
if (!user.is_loaded)
return;
- let userName = user.get_user_name();
+ const userName = user.get_user_name();
if (!userName)
return;
Signals: {'session-activated': {param_types: [GObject.TYPE_STRING]}},
}, class SessionMenuButton extends St.Bin {
_init() {
- let button = new St.Button({
+ const button = new St.Button({
style_class: 'login-dialog-button login-dialog-session-list-button',
icon_name: 'cog-wheel-symbolic',
reactive: true,
}
_populate() {
- let ids = Gdm.get_session_ids();
+ const ids = Gdm.get_session_ids();
if (ids.length <= 1) {
this._button.hide();
sessions.sort((a, b) => a.sessionName.localeCompare(b.sessionName));
for (const {id, sessionName} of sessions) {
- let item = new PopupMenu.PopupMenuItem(sessionName);
+ const item = new PopupMenu.PopupMenuItem(sessionName);
this._menu.addMenuItem(item);
this._items.set(id, item);
/* Translators: is running for <username> */
bannerText = _('Login is not possible because a session is already running for %s. To login, you must log out from the session or force stop it.').format(userName);
- let textLayout = new St.BoxLayout({
+ const textLayout = new St.BoxLayout({
style_class: 'conflicting-session-dialog-content',
orientation: Clutter.Orientation.VERTICAL,
x_expand: true,
});
- let title = new St.Label({
+ const title = new St.Label({
text: _('Session Already Running'),
style_class: 'conflicting-session-dialog-title',
});
- let banner = new St.Label({
+ const banner = new St.Label({
text: bannerText,
style_class: 'conflicting-session-dialog-desc',
});
banner.clutter_text.ellipsize = Pango.EllipsizeMode.NONE;
banner.clutter_text.line_wrap = true;
- let warningBanner = new St.Label({
+ const warningBanner = new St.Label({
text: _('Force stopping will quit any running apps and processes, and could result in data loss'),
style_class: 'conflicting-session-dialog-desc-warning',
});
// translators: this message is shown below the user list on the
// login screen. It can be activated to reveal an entry for
// manually entering the username.
- let notListedLabel = new St.Label({
+ const notListedLabel = new St.Label({
text: _('Not listed?'),
style_class: 'login-dialog-not-listed-label',
});
}
_getBannerAllocation(dialogBox) {
- let actorBox = new Clutter.ActorBox();
+ const actorBox = new Clutter.ActorBox();
- let [, , natWidth, natHeight] = this._bannerView.get_preferred_size();
- let centerX = dialogBox.x1 + (dialogBox.x2 - dialogBox.x1) / 2;
+ const [, , natWidth, natHeight] = this._bannerView.get_preferred_size();
+ const centerX = dialogBox.x1 + (dialogBox.x2 - dialogBox.x1) / 2;
actorBox.x1 = Math.floor(centerX - natWidth / 2);
actorBox.y1 = dialogBox.y1 + Main.layoutManager.panelBox.height;
}
_getLogoBinAllocation(dialogBox) {
- let actorBox = new Clutter.ActorBox();
+ const actorBox = new Clutter.ActorBox();
- let [, , natWidth, natHeight] = this._logoBin.get_preferred_size();
- let centerX = dialogBox.x1 + (dialogBox.x2 - dialogBox.x1) / 2;
+ const [, , natWidth, natHeight] = this._logoBin.get_preferred_size();
+ const centerX = dialogBox.x1 + (dialogBox.x2 - dialogBox.x1) / 2;
actorBox.x1 = Math.floor(centerX - natWidth / 2);
actorBox.y1 = dialogBox.y2 - natHeight;
}
_getBottomButtonGroupAllocation(dialogBox) {
- let actorBox = new Clutter.ActorBox();
+ const actorBox = new Clutter.ActorBox();
const [, , natWidth, natHeight] = this._bottomButtonGroup.get_preferred_size();
}
_getCenterActorAllocation(dialogBox, actor) {
- let actorBox = new Clutter.ActorBox();
+ const actorBox = new Clutter.ActorBox();
let [, , natWidth, natHeight] = actor.get_preferred_size();
- let centerX = dialogBox.x1 + (dialogBox.x2 - dialogBox.x1) / 2;
- let centerY = dialogBox.y1 + (dialogBox.y2 - dialogBox.y1) / 2;
+ const centerX = dialogBox.x1 + (dialogBox.x2 - dialogBox.x1) / 2;
+ const centerY = dialogBox.y1 + (dialogBox.y2 - dialogBox.y1) / 2;
natWidth = Math.min(natWidth, dialogBox.x2 - dialogBox.x1);
natHeight = Math.min(natHeight, dialogBox.y2 - dialogBox.y1);
vfunc_allocate(dialogBox) {
this.set_allocation(dialogBox);
- let themeNode = this.get_theme_node();
+ const themeNode = this.get_theme_node();
dialogBox = themeNode.get_content_box(dialogBox);
- let dialogWidth = dialogBox.x2 - dialogBox.x1;
- let dialogHeight = dialogBox.y2 - dialogBox.y1;
+ const dialogWidth = dialogBox.x2 - dialogBox.x1;
+ const dialogHeight = dialogBox.y2 - dialogBox.y1;
// First find out what space the children require
let bannerAllocation = null;
if (leftOverYSpace > 0) {
// First figure out how much left over space is up top
- let leftOverTopSpace = leftOverYSpace / 2;
+ const leftOverTopSpace = leftOverYSpace / 2;
// Then, shift the banner into the middle of that extra space
- let yShift = Math.floor(leftOverTopSpace / 2);
+ const yShift = Math.floor(leftOverTopSpace / 2);
bannerAllocation.y1 += yShift;
bannerAllocation.y2 += yShift;
} else {
// Then figure out how much space there would be if we switched to a
// wide layout with banner on one side and authprompt on the other.
- let leftOverXSpace = dialogWidth - authPromptWidth;
+ const leftOverXSpace = dialogWidth - authPromptWidth;
// In a wide view, half of the available space goes to the banner,
// and the other half goes to the margins.
- let wideBannerWidth = leftOverXSpace / 2;
- let wideSpacing = leftOverXSpace - wideBannerWidth;
+ const wideBannerWidth = leftOverXSpace / 2;
+ const wideSpacing = leftOverXSpace - wideBannerWidth;
// If we do go with a wide layout, we need there to be at least enough
// space for the banner and the auth prompt to be the same width,
// so it doesn't look unbalanced.
if (authPromptWidth > 0 && wideBannerWidth > authPromptWidth) {
- let centerX = dialogBox.x1 + dialogWidth / 2;
- let centerY = dialogBox.y1 + dialogHeight / 2;
+ const centerX = dialogBox.x1 + dialogWidth / 2;
+ const centerY = dialogBox.y1 + dialogHeight / 2;
// A small portion of the spacing goes down the center of the
// screen to help delimit the two columns of the wide view
- let centerGap = wideSpacing / 8;
+ const centerGap = wideSpacing / 8;
// place the banner along the left edge of the center margin
bannerAllocation.x2 = Math.floor(centerX - centerGap / 2);
// but don't let it get too close to the logo
let [, wideBannerHeight] = this._bannerView.get_preferred_height(wideBannerWidth);
- let maxWideHeight = dialogHeight - 3 * logoHeight;
+ const maxWideHeight = dialogHeight - 3 * logoHeight;
wideBannerHeight = Math.min(maxWideHeight, wideBannerHeight);
bannerAllocation.y1 = Math.floor(centerY - wideBannerHeight / 2);
bannerAllocation.y2 = bannerAllocation.y1 + wideBannerHeight;
leftOverYSpace += bannerHeight;
// Then figure out how much of that space is up top
- let availableTopSpace = Math.floor(leftOverYSpace / 2);
+ const availableTopSpace = Math.floor(leftOverYSpace / 2);
// Then give all of that space to the banner
bannerAllocation.y2 = bannerAllocation.y1 + availableTopSpace;
}
} else if (userSelectionAllocation) {
// Grow the user list to fill the space
- let leftOverYSpace = dialogHeight - userSelectionHeight - logoHeight;
+ const leftOverYSpace = dialogHeight - userSelectionHeight - logoHeight;
if (leftOverYSpace > 0) {
- let topExpansion = Math.floor(leftOverYSpace / 2);
- let bottomExpansion = topExpansion;
+ const topExpansion = Math.floor(leftOverYSpace / 2);
+ const bottomExpansion = topExpansion;
userSelectionAllocation.y1 -= topExpansion;
userSelectionAllocation.y2 += bottomExpansion;
}
});
} else {
- let id = GLib.idle_add(GLib.PRIORITY_DEFAULT, this._loadUserList.bind(this));
+ const id = GLib.idle_add(GLib.PRIORITY_DEFAULT, this._loadUserList.bind(this));
GLib.Source.set_name_by_id(id, '[gnome-shell] _loadUserList');
}
}
}
_updateLogo() {
- let path = this._settings.get_string(GdmUtil.LOGO_KEY);
+ const path = this._settings.get_string(GdmUtil.LOGO_KEY);
this._logoFile = path ? Gio.file_new_for_path(path) : null;
this._updateLogoTexture(this._textureCache, this._logoFile);
this._authPrompt.disconnect(this._nextSignalId);
this._nextSignalId = 0;
this._authPrompt.updateSensitivity(false);
- let answer = this._authPrompt.getAnswer();
+ const answer = this._authPrompt.getAnswer();
this._user = this._userManager.get_user(answer);
this._authPrompt.clear();
this._authPrompt.begin({userName: answer});
}
_showConflictingSessionDialog(serviceName, conflictingSession) {
- let conflictingSessionDialog = new ConflictingSessionDialog(conflictingSession,
+ const conflictingSessionDialog = new ConflictingSessionDialog(conflictingSession,
this._greeterSessionProxy);
conflictingSessionDialog.connect('cancel', () => {
if (item)
return null;
- let hold = new Batch.Hold();
- let signalId = this._userList.connect('item-added',
+ const hold = new Batch.Hold();
+ const signalId = this._userList.connect('item-added',
() => {
item = this._userList.getItemFromUserName(userName);
}
_blockTimedLoginUntilIdle() {
- let hold = new Batch.Hold();
+ const hold = new Batch.Hold();
this._timedLoginIdleTimeOutId = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, _TIMED_LOGIN_IDLE_THRESHOLD,
() => {
let loginItem = null;
let animationTime;
- let tasks = [
+ const tasks = [
() => {
if (this._disableUserList)
return null;
_beginVerificationForItem(item) {
this._authPrompt.setUser(item.user);
- let userName = item.user.get_user_name();
- let hold = new Batch.Hold();
+ const userName = item.user.get_user_name();
+ const hold = new Batch.Hold();
this._authPrompt.begin({userName, hold});
return hold;
this._userListLoaded = true;
- let users = this._userManager.list_users();
+ const users = this._userManager.list_users();
for (let i = 0; i < users.length; i++)
this._userList.addUser(users[i]);
}
_reloadRealms() {
- let realmPaths = this._aggregateProvider.Realms;
+ const realmPaths = this._aggregateProvider.Realms;
if (!realmPaths)
return;
_updateLoginFormat() {
let newLoginFormat;
- for (let realmPath in this._realms) {
- let realm = this._realms[realmPath];
+ for (const realmPath in this._realms) {
+ const realm = this._realms[realmPath];
if (realm.LoginFormats && realm.LoginFormats.length > 0) {
newLoginFormat = realm.LoginFormats[0];
break;
Main.uiGroup.add_child(clone);
- let [x, y] = actor.get_transformed_position();
+ const [x, y] = actor.get_transformed_position();
clone.set_position(x, y);
- let hold = new Batch.Hold();
+ const hold = new Batch.Hold();
clone.ease({
opacity: 0,
duration: CLONE_FADE_ANIMATION_TIME,
}
removeCredentialManager(serviceName) {
- let credentialManager = this._credentialManagers[serviceName];
+ const credentialManager = this._credentialManagers[serviceName];
if (!credentialManager)
return;
this._fingerprintManager = null;
- for (let service in this._credentialManagers)
+ for (const service in this._credentialManagers)
this.removeCredentialManager(service);
}
}
_queueMessage(serviceName, message, messageType) {
- let interval = this._getIntervalForMessage(message);
+ const interval = this._getIntervalForMessage(message);
this._messageQueue.push({serviceName, text: message, type: messageType, interval});
this._queueMessageTimeout();
}
foregroundServiceDeterminesUsername() {
- for (let serviceName in this._credentialManagers) {
+ for (const serviceName in this._credentialManagers) {
if (this.serviceIsForeground(serviceName))
return true;
}
const cancellable = this._cancellable;
return new Promise((resolve, reject) => {
- let signalId = this.connect('no-more-messages', () => {
+ const signalId = this.connect('no-more-messages', () => {
this.disconnect(signalId);
if (cancellable.is_cancelled())
reject(new GLib.Error(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED, 'Operation was cancelled'));
getNextBreakDue(fromTime) {
let maxDuration = 0;
let maxDurationType = null;
- let dueBreakTypes = [];
+ const dueBreakTypes = [];
let nextDueTime = 0;
console.debug(`BreakManager: Current time: ${fromTime}s`);
}
_position() {
- let workArea = Main.layoutManager.getWorkAreaForMonitor(Main.layoutManager.primaryIndex);
+ const workArea = Main.layoutManager.getWorkAreaForMonitor(Main.layoutManager.primaryIndex);
if (Clutter.get_default_text_direction() === Clutter.TextDirection.RTL)
this._box.x = workArea.x + (workArea.width - this._box.width);
return;
// don't use global.datadir so the method is usable from tests/tools
- let dir = GLib.getenv('GNOME_SHELL_DATADIR') || Config.PKGDATADIR;
- let path = `${dir}/gnome-shell-dbus-interfaces.gresource`;
+ const dir = GLib.getenv('GNOME_SHELL_DATADIR') || Config.PKGDATADIR;
+ const path = `${dir}/gnome-shell-dbus-interfaces.gresource`;
_ifaceResource = Gio.Resource.load(path);
_ifaceResource._register();
}
export function loadInterfaceXML(iface) {
_ensureIfaceResource();
- let uri = `resource:///org/gnome/shell/dbus-interfaces/${iface}.xml`;
- let f = Gio.File.new_for_uri(uri);
+ const uri = `resource:///org/gnome/shell/dbus-interfaces/${iface}.xml`;
+ const f = Gio.File.new_for_uri(uri);
try {
- let [ok_, bytes] = f.load_contents(null);
+ const [ok_, bytes] = f.load_contents(null);
return new TextDecoder().decode(bytes);
} catch {
log(`Failed to load D-Bus interface ${iface}`);
* @returns {string | null} the XML string or null if it is not found
*/
export function loadSubInterfaceXML(iface, ifaceFile) {
- let xml = loadInterfaceXML(ifaceFile);
+ const xml = loadInterfaceXML(ifaceFile);
if (!xml)
return null;
- let ifaceStartTag = `<interface name="${iface}">`;
- let ifaceStopTag = '</interface>';
- let ifaceStartIndex = xml.indexOf(ifaceStartTag);
- let ifaceEndIndex = xml.indexOf(ifaceStopTag, ifaceStartIndex + 1) + ifaceStopTag.length;
+ const ifaceStartTag = `<interface name="${iface}">`;
+ const ifaceStopTag = '</interface>';
+ const ifaceStartIndex = xml.indexOf(ifaceStartTag);
+ const ifaceEndIndex = xml.indexOf(ifaceStopTag, ifaceStartIndex + 1) + ifaceStopTag.length;
- let xmlHeader = '<!DOCTYPE node PUBLIC\n' +
+ const xmlHeader = '<!DOCTYPE node PUBLIC\n' +
'\'-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\'\n' +
'\'http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\'>\n' +
'<node>\n';
- let xmlFooter = '</node>';
+ const xmlFooter = '</node>';
return (
xmlHeader +
* @returns {object}
*/
export function serializeExtension(extension) {
- let obj = {...extension.metadata};
+ const obj = {...extension.metadata};
SERIALIZED_PROPERTIES.forEach(prop => {
obj[prop] = extension[prop];
val = val.map(v => packValue(v));
} else {
type = 'a{sv}';
- let res = {};
- for (let key in val) {
- let packed = packValue(val[key]);
+ const res = {};
+ for (const key in val) {
+ const packed = packValue(val[key]);
if (packed)
res[key] = packed;
}
* @returns {object}
*/
export function deserializeExtension(variant) {
- let res = {metadata: {}};
- for (let prop in variant) {
- let val = variant[prop].recursiveUnpack();
+ const res = {metadata: {}};
+ for (const prop in variant) {
+ const val = variant[prop].recursiveUnpack();
if (SERIALIZED_PROPERTIES.includes(prop))
res[prop] = val;
else
* `subdir` within data directories
*/
export function* collectFromDatadirs(subdir, includeUserDir) {
- let dataDirs = GLib.get_system_data_dirs();
+ const dataDirs = GLib.get_system_data_dirs();
if (includeUserDir)
dataDirs.unshift(GLib.get_user_data_dir());
for (let i = 0; i < dataDirs.length; i++) {
- let path = GLib.build_filenamev([dataDirs[i], 'gnome-shell', subdir]);
- let dir = Gio.File.new_for_path(path);
+ const path = GLib.build_filenamev([dataDirs[i], 'gnome-shell', subdir]);
+ const dir = Gio.File.new_for_path(path);
let fileEnum;
try {
* @param {boolean} deleteParent
*/
export function recursivelyDeleteDir(dir, deleteParent) {
- let children = dir.enumerate_children('standard::name,standard::type',
+ const children = dir.enumerate_children('standard::name,standard::type',
Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS, null);
let info;
while ((info = children.next_file(null)) != null) {
- let type = info.get_file_type();
- let child = dir.get_child(info.get_name());
+ const type = info.get_file_type();
+ const child = dir.get_child(info.get_name());
if (type === Gio.FileType.REGULAR || type === Gio.FileType.SYMBOLIC_LINK)
child.delete(null);
else if (type === Gio.FileType.DIRECTORY)
* @param {Gio.File} destDir
*/
export function recursivelyMoveDir(srcDir, destDir) {
- let children = srcDir.enumerate_children('standard::name,standard::type',
+ const children = srcDir.enumerate_children('standard::name,standard::type',
Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS, null);
if (!destDir.query_exists(null))
let info;
while ((info = children.next_file(null)) != null) {
- let type = info.get_file_type();
- let srcChild = srcDir.get_child(info.get_name());
- let destChild = destDir.get_child(info.get_name());
+ const type = info.get_file_type();
+ const srcChild = srcDir.get_child(info.get_name());
+ const destChild = destDir.get_child(info.get_name());
if (type === Gio.FileType.REGULAR || type === Gio.FileType.SYMBOLIC_LINK)
srcChild.move(destChild, Gio.FileCopyFlags.NONE, null, null);
else if (type === Gio.FileType.DIRECTORY)
}
_onEntryKeyPress(entry, event) {
- let symbol = event.get_key_symbol();
+ const symbol = event.get_key_symbol();
if (symbol === Clutter.KEY_Up)
return this._setPrevItem(entry.get_text().trim());
else if (symbol === Clutter.KEY_Down)
}
_indexChanged() {
- let current = this._history[this._historyIndex] || '';
+ const current = this._history[this._historyIndex] || '';
this.emit('changed', current);
if (this._entry)
const enginesList =
await this._ibus.list_engines_async(-1, this._cancellable);
for (let i = 0; i < enginesList.length; ++i) {
- let name = enginesList[i].get_name();
+ const name = enginesList[i].get_name();
this._engines.set(name, enginesList[i]);
}
this._updateReadiness();
this._candidatePopup.setPanelService(this._panelService);
this._panelService.connect('update-property', this._updateProperty.bind(this));
this._panelService.connect('set-cursor-location', (ps, x, y, w, h) => {
- let cursorLocation = {x, y, width: w, height: h};
+ const cursorLocation = {x, y, width: w, height: h};
this.emit('set-cursor-location', cursorLocation);
});
this._panelService.connect('focus-in', (panel, path) => {
}
_onForwardKeyEvent(_context, keyval, keycode, state) {
- let press = (state & IBus.ModifierType.RELEASE_MASK) === 0;
+ const press = (state & IBus.ModifierType.RELEASE_MASK) === 0;
state &= ~IBus.ModifierType.RELEASE_MASK;
- let curEvent = Clutter.get_current_event();
+ const curEvent = Clutter.get_current_event();
let time;
if (curEvent)
time = curEvent.get_time();
if (!this._context || (!text && text !== ''))
return;
- let ibusText = IBus.Text.new_from_string(text);
+ const ibusText = IBus.Text.new_from_string(text);
if (updateCapabilities)
this._updateCapabilities();
return;
try {
- let retval = context.process_key_event_async_finish(res);
+ const retval = context.process_key_event_async_finish(res);
this.notify_key_event(event, retval);
} catch (e) {
if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
this._syncRunningApplications();
});
- let tracker = Shell.WindowTracker.get_default();
+ const tracker = Shell.WindowTracker.get_default();
tracker.connect('notify::focus-app', () => {
this._activeApplicationDirty = true;
this._syncRunningApplications();
}
_getSandboxedAppId(app) {
- let ids = app.get_windows().map(w => w.get_sandboxed_app_id());
+ const ids = app.get_windows().map(w => w.get_sandboxed_app_id());
return ids.find(id => id != null);
}
_syncRunningApplications() {
- let tracker = Shell.WindowTracker.get_default();
- let apps = this._appSystem.get_running();
- let seatName = 'seat0';
- let newRunningApplications = {};
+ const tracker = Shell.WindowTracker.get_default();
+ const apps = this._appSystem.get_running();
+ const seatName = 'seat0';
+ const newRunningApplications = {};
let newActiveApplication = null;
- let focusedApp = tracker.focus_app;
+ const focusedApp = tracker.focus_app;
- for (let app of apps) {
- let appInfo = {};
- let isAppActive = focusedApp === app;
+ for (const app of apps) {
+ const appInfo = {};
+ const isAppActive = focusedApp === app;
if (!this._isStandaloneApp(app))
continue;
newActiveApplication = app.get_id();
}
- let sandboxedAppId = this._getSandboxedAppId(app);
+ const sandboxedAppId = this._getSandboxedAppId(app);
if (sandboxedAppId)
appInfo['sandboxed-app-id'] = new GLib.Variant('s', sandboxedAppId);
if (window.is_override_redirect())
return false;
- let type = window.get_window_type();
+ const type = window.get_window_type();
return type === Meta.WindowType.NORMAL ||
type === Meta.WindowType.DIALOG ||
type === Meta.WindowType.MODAL_DIALOG ||
}
async GetWindowsAsync(params, invocation) {
- let focusWindow = global.display.get_focus_window();
- let apps = this._appSystem.get_running();
- let windowsList = {};
+ const focusWindow = global.display.get_focus_window();
+ const apps = this._appSystem.get_running();
+ const windowsList = {};
try {
await this._senderChecker.checkInvocation(invocation);
return;
}
- for (let app of apps) {
- let windows = app.get_windows();
- for (let window of windows) {
+ for (const app of apps) {
+ const windows = app.get_windows();
+ for (const window of windows) {
if (!this._isEligibleWindow(window))
continue;
- let windowId = window.get_id();
- let frameRect = window.get_frame_rect();
- let title = window.get_title();
- let wmClass = window.get_wm_class();
- let sandboxedAppId = window.get_sandboxed_app_id();
+ const windowId = window.get_id();
+ const frameRect = window.get_frame_rect();
+ const title = window.get_title();
+ const wmClass = window.get_wm_class();
+ const sandboxedAppId = window.get_sandboxed_app_id();
windowsList[windowId] = {
'app-id': GLib.Variant.new('s', app.get_id()),
}
_syncAnimationsEnabled() {
- let wasAnimationsEnabled = this._animationsEnabled;
+ const wasAnimationsEnabled = this._animationsEnabled;
this._animationsEnabled = this._settings.enable_animations;
if (wasAnimationsEnabled !== this._animationsEnabled) {
- let variant = new GLib.Variant('b', this._animationsEnabled);
+ const variant = new GLib.Variant('b', this._animationsEnabled);
this._dbusImpl.emit_property_changed('AnimationsEnabled', variant);
}
}
if (globalCompletionList == null)
globalCompletionList = [];
- let offset = getExpressionOffset(text, text.length - 1);
+ const offset = getExpressionOffset(text, text.length - 1);
if (offset >= 0) {
text = text.slice(offset);
* @param {number} offset
*/
export function findMatchingQuote(expr, offset) {
- let quoteChar = expr.charAt(offset);
+ const quoteChar = expr.charAt(offset);
for (let i = offset - 1; i >= 0; --i) {
if (expr.charAt(i) === quoteChar && expr.charAt(i - 1) !== '\\')
return i;
* @param {number} offset
*/
export function findMatchingBrace(expr, offset) {
- let closeBrace = expr.charAt(offset);
- let openBrace = {')': '(', ']': '['}[closeBrace];
+ const closeBrace = expr.charAt(offset);
+ const openBrace = {')': '(', ']': '['}[closeBrace];
return findTheBrace(expr, offset - 1, openBrace, closeBrace);
}
* @returns {number}
*/
export function findTheBrace(expr, offset, ...braces) {
- let [openBrace, closeBrace] = braces;
+ const [openBrace, closeBrace] = braces;
if (offset < 0)
return -1;
*/
export function getExpressionOffset(expr, offset) {
while (offset >= 0) {
- let currChar = expr.charAt(offset);
+ const currChar = expr.charAt(offset);
if (isStopChar(currChar))
return offset + 1;
return [];
}
- let propsUnique = {};
+ const propsUnique = {};
if (typeof obj === 'object') {
let allProps = getAllProps(obj);
// Get only things we are allowed to complete following a '.'
* @param {readonly string[]} words
*/
export function getCommonPrefix(words) {
- let word = words[0];
+ const word = words[0];
for (let i = 0; i < word.length; i++) {
for (let w = 1; w < words.length; w++) {
if (words[w].charAt(i) !== word.charAt(i))
if (str.length === 0)
return '';
- let currChar = str.charAt(str.length - 1);
+ const currChar = str.charAt(str.length - 1);
if (currChar === '"' || currChar === '\'') {
return removeLiterals(
str.slice(0, findMatchingQuote(str, str.length - 1)));
* @param {string} str
*/
export function getDeclaredConstants(str) {
- let ret = [];
+ const ret = [];
str.split(';').forEach(s => {
let base_, keyword;
- let match = s.match(/const\s+(\w+)\s*=/);
+ const match = s.match(/const\s+(\w+)\s*=/);
if (match) {
[base_, keyword] = match;
ret.push(keyword);
}
async _applyLayoutGroup(group) {
- let options = this._buildOptionsString();
- let [layouts, variants] = this._buildGroupStrings(group);
- let model = this._xkbModel;
+ const options = this._buildOptionsString();
+ const [layouts, variants] = this._buildGroupStrings(group);
+ const model = this._xkbModel;
if (this._currentKeymap &&
this._currentKeymap.layouts === layouts &&
}
apply(id) {
- let info = this._layoutInfos[id];
+ const info = this._layoutInfos[id];
if (!info)
return;
this._layoutInfos = {};
for (const id of ids) {
- let [found, , , layout, variant] = this._xkbInfo.get_layout_info(id);
+ const [found, , , layout, variant] = this._xkbInfo.get_layout_info(id);
if (found)
this._layoutInfos[id] = {id, layout, variant};
}
let i = 0;
let group = [];
- for (let id in this._layoutInfos) {
+ for (const id in this._layoutInfos) {
// We need to leave one slot on each group free so that we
// can add a layout containing the symbols for the
// language used in UI strings to ensure that toolkits can
// handle mnemonics like Alt+Ф even if the user is
// actually typing in a different layout.
- let groupIndex = i % (this.MAX_LAYOUTS_PER_GROUP - 1);
+ const groupIndex = i % (this.MAX_LAYOUTS_PER_GROUP - 1);
if (groupIndex === 0)
group = [];
- let info = this._layoutInfos[id];
+ const info = this._layoutInfos[id];
group[groupIndex] = info;
info.group = group;
info.groupIndex = groupIndex;
}
_buildGroupStrings(_group) {
- let group = _group.concat(this._localeLayoutInfo);
- let layouts = group.map(g => g.layout).join(',');
- let variants = group.map(g => g.variant).join(',');
+ const group = _group.concat(this._localeLayoutInfo);
+ const layouts = group.map(g => g.layout).join(',');
+ const variants = group.map(g => g.variant).join(',');
return [layouts, variants];
}
}
_buildOptionsString() {
- let options = this._xkbOptions.join(',');
+ const options = this._xkbOptions.join(',');
return options;
}
reference = reference.split('.');
for (let i = 0; i < required.length; i++) {
- let requiredInt = parseInt(required[i]);
- let referenceInt = parseInt(reference[i]);
+ const requiredInt = parseInt(required[i]);
+ const referenceInt = parseInt(reference[i]);
if (requiredInt !== referenceInt)
return requiredInt < referenceInt;
}
*/
export function canLock() {
try {
- let params = GLib.Variant.new('(ss)', ['org.gnome.DisplayManager.Manager', 'Version']);
- let result = Gio.DBus.system.call_sync(
+ const params = GLib.Variant.new('(ss)', ['org.gnome.DisplayManager.Manager', 'Version']);
+ const result = Gio.DBus.system.call_sync(
'org.gnome.DisplayManager',
'/org/gnome/DisplayManager/Manager',
'org.freedesktop.DBus.Properties',
Gio.DBusCallFlags.NONE,
-1, null);
- let version = result.deepUnpack()[0].deepUnpack();
+ const version = result.deepUnpack()[0].deepUnpack();
return haveSystemd() && versionCompare('3.5.91', version);
} catch {
return false;
log('Failed to find "Display" session; are we the greeter?');
for ([session, objectPath] of userProxy.Sessions) {
- let sessionProxy = new SystemdLoginSession(Gio.DBus.system,
+ const sessionProxy = new SystemdLoginSession(Gio.DBus.system,
'org.freedesktop.login1',
objectPath);
log(`Considering ${session}, class=${sessionProxy.Class}`);
else // nothing to search
return null;
- let mpd = _getMobileProvidersDatabase();
+ const mpd = _getMobileProvidersDatabase();
if (mpd) {
- let provider = mpd.lookup_3gpp_mcc_mnc(needle);
+ const provider = mpd.lookup_3gpp_mcc_mnc(needle);
if (provider)
return provider.get_name();
}
if (!sid)
return null;
- let mpd = _getMobileProvidersDatabase();
+ const mpd = _getMobileProvidersDatabase();
if (mpd) {
- let provider = mpd.lookup_cdma_sid(sid);
+ const provider = mpd.lookup_cdma_sid(sid);
if (provider)
return provider.get_name();
}
this._reloadSignalQuality();
this._proxy_3gpp.connect('g-properties-changed', (proxy, properties) => {
- let unpacked = properties.deepUnpack();
+ const unpacked = properties.deepUnpack();
if ('OperatorName' in unpacked || 'OperatorCode' in unpacked)
this._reload3gppOperatorName();
});
this._reload3gppOperatorName();
this._proxy_cdma.connect('g-properties-changed', (proxy, properties) => {
- let unpacked = properties.deepUnpack();
+ const unpacked = properties.deepUnpack();
if ('Nid' in unpacked || 'Sid' in unpacked)
this._reloadCdmaOperatorName();
});
}
_reloadSignalQuality() {
- let [quality, recent_] = this._proxy.SignalQuality;
+ const [quality, recent_] = this._proxy.SignalQuality;
this._setSignalQuality(quality);
}
}
_reload3gppOperatorName() {
- let name = this._proxy_3gpp.OperatorName;
- let code = this._proxy_3gpp.OperatorCode;
+ const name = this._proxy_3gpp.OperatorName;
+ const code = this._proxy_3gpp.OperatorCode;
this.operator_name_3gpp = _findProviderForMccMnc(name, code);
this._reloadOperatorName();
}
_reloadCdmaOperatorName() {
- let sid = this._proxy_cdma.Sid;
+ const sid = this._proxy_cdma.Sid;
this.operator_name_cdma = _findProviderForSid(sid);
this._reloadOperatorName();
}
}
async _addInterface(objectPath, interfaceName) {
- let info = this._interfaceInfos[interfaceName];
+ const info = this._interfaceInfos[interfaceName];
if (!info)
return;
if (!this._objects[objectPath])
return;
- let proxy = this._objects[objectPath][interfaceName];
+ const proxy = this._objects[objectPath][interfaceName];
if (this._interfaces[interfaceName]) {
- let index = this._interfaces[interfaceName].indexOf(proxy);
+ const index = this._interfaces[interfaceName].indexOf(proxy);
if (index >= 0)
this._interfaces[interfaceName].splice(index, 1);
this._managerProxy.connectSignal('InterfacesAdded',
(objectManager, sender, [objectPath, interfaces]) => {
- let interfaceNames = Object.keys(interfaces);
+ const interfaceNames = Object.keys(interfaces);
for (let i = 0; i < interfaceNames.length; i++)
this._addInterface(objectPath, interfaceNames[i]);
});
}
_onNameVanished() {
- let objectPaths = Object.keys(this._objects);
+ const objectPaths = Object.keys(this._objects);
for (let i = 0; i < objectPaths.length; i++) {
- let objectPath = objectPaths[i];
- let object = this._objects[objectPath];
+ const objectPath = objectPaths[i];
+ const object = this._objects[objectPath];
- let interfaceNames = Object.keys(object);
+ const interfaceNames = Object.keys(object);
for (let j = 0; j < interfaceNames.length; j++) {
- let interfaceName = interfaceNames[j];
+ const interfaceName = interfaceNames[j];
if (object[interfaceName])
this._removeInterface(objectPath, interfaceName);
_registerInterfaces(interfaces) {
for (let i = 0; i < interfaces.length; i++) {
- let info = Gio.DBusInterfaceInfo.new_for_xml(interfaces[i]);
+ const info = Gio.DBusInterfaceInfo.new_for_xml(interfaces[i]);
this._interfaceInfos[info.name] = info;
}
}
getProxy(objectPath, interfaceName) {
- let object = this._objects[objectPath];
+ const object = this._objects[objectPath];
if (!object)
return null;
}
getProxiesForInterface(interfaceName) {
- let proxyList = this._interfaces[interfaceName];
+ const proxyList = this._interfaces[interfaceName];
if (!proxyList)
return [];
}
getAllProxies() {
- let proxies = [];
+ const proxies = [];
- let objectPaths = Object.keys(this._objects);
+ const objectPaths = Object.keys(this._objects);
for (let i = 0; i < objectPaths.length; i++) {
- let object = this._objects[objectPaths];
+ const object = this._objects[objectPaths];
- let interfaceNames = Object.keys(object);
+ const interfaceNames = Object.keys(object);
for (let j = 0; j < interfaceNames.length; j++) {
- let interfaceName = interfaceNames[j];
+ const interfaceName = interfaceNames[j];
if (object[interfaceName])
proxies.push(object(interfaceName));
}
*/
export function parse(params = {}, defaults, allowExtras) {
if (!allowExtras) {
- for (let prop in params) {
+ for (const prop in params) {
if (!(prop in defaults))
throw new Error(`Unrecognized parameter "${prop}"`);
}
async _onAppFilterChanged(manager, uid) {
// Emit 'changed' signal only if app-filter is changed for currently logged-in user.
- let currentUid = Shell.util_get_uid();
+ const currentUid = Shell.util_get_uid();
if (currentUid !== uid)
return;
}
_onLoaded() {
- let tokens = this._objectManager.getProxiesForInterface('org.gnome.SettingsDaemon.Smartcard.Token');
+ const tokens = this._objectManager.getProxiesForInterface('org.gnome.SettingsDaemon.Smartcard.Token');
for (let i = 0; i < tokens.length; i++)
this._addToken(tokens[i]);
}
_updateToken(token) {
- let objectPath = token.get_object_path();
+ const objectPath = token.get_object_path();
delete this._insertedTokens[objectPath];
}
_removeToken(token) {
- let objectPath = token.get_object_path();
+ const objectPath = token.get_object_path();
if (this._insertedTokens[objectPath] === token) {
delete this._insertedTokens[objectPath];
}
_updateOrientationLockStatus() {
- let locked = this._orientationSettings.get_boolean('orientation-lock');
- let action = this._actions.get(LOCK_ORIENTATION_ACTION_ID);
+ const locked = this._orientationSettings.get_boolean('orientation-lock');
+ const action = this._actions.get(LOCK_ORIENTATION_ACTION_ID);
// Translators: The name of the lock orientation action in search
// and in the system status menu
- let name = locked
+ const name = locked
? C_('search-result', 'Unlock Screen Rotation')
: C_('search-result', 'Lock Screen Rotation');
- let iconName = locked
+ const iconName = locked
? 'rotation-locked-symbolic'
: 'rotation-allowed-symbolic';
if (terms.length === 0)
return [];
- let results = [];
+ const results = [];
- for (let [key, {available, keywords}] of this._actions) {
+ for (const [key, {available, keywords}] of this._actions) {
if (available && terms.every(t => keywords.some(k => k.startsWith(t))))
results.push(key);
}
}
_updateLockScreen() {
- let showLock = !Main.sessionMode.isLocked && !Main.sessionMode.isGreeter;
- let allowLockScreen = !this._lockdownSettings.get_boolean(DISABLE_LOCK_SCREEN_KEY);
+ const showLock = !Main.sessionMode.isLocked && !Main.sessionMode.isGreeter;
+ const allowLockScreen = !this._lockdownSettings.get_boolean(DISABLE_LOCK_SCREEN_KEY);
this._actions.get(LOCK_SCREEN_ACTION_ID).available = showLock && allowLockScreen && LoginManager.canLock();
this.notify('can-lock-screen');
}
}
_updatePowerOff() {
- let disabled = (Main.sessionMode.isLocked &&
+ const disabled = (Main.sessionMode.isLocked &&
!this._screenSaverSettings.get_boolean(RESTART_ENABLED_KEY)) ||
(Main.sessionMode.isGreeter &&
this._loginScreenSettings.get_boolean(DISABLE_RESTART_KEY));
}
_updateSuspend() {
- let disabled = (Main.sessionMode.isLocked &&
+ const disabled = (Main.sessionMode.isLocked &&
this._suspendNeedsAuth) ||
(Main.sessionMode.isGreeter &&
this._loginScreenSettings.get_boolean(DISABLE_RESTART_KEY));
}
_updateSwitchUser() {
- let allowSwitch = !this._lockdownSettings.get_boolean(DISABLE_USER_SWITCH_KEY);
- let multiUser = this._userManager.can_switch() && this._userManager.has_multiple_users;
- let shouldShowInMode = !Main.sessionMode.isLocked && !Main.sessionMode.isGreeter;
+ const allowSwitch = !this._lockdownSettings.get_boolean(DISABLE_USER_SWITCH_KEY);
+ const multiUser = this._userManager.can_switch() && this._userManager.has_multiple_users;
+ const shouldShowInMode = !Main.sessionMode.isLocked && !Main.sessionMode.isGreeter;
- let visible = allowSwitch && multiUser && shouldShowInMode;
+ const visible = allowSwitch && multiUser && shouldShowInMode;
this._actions.get(SWITCH_USER_ACTION_ID).available = visible;
this.notify('can-switch-user');
}
_updateLogout() {
- let user = this._userManager.get_user(GLib.get_user_name());
+ const user = this._userManager.get_user(GLib.get_user_name());
- let allowLogout = !this._lockdownSettings.get_boolean(DISABLE_LOG_OUT_KEY);
- let alwaysShow = global.settings.get_boolean(ALWAYS_SHOW_LOG_OUT_KEY);
- let systemAccount = user.system_account;
- let localAccount = user.local_account;
- let multiUser = this._userManager.has_multiple_users;
- let multiSession = Gdm.get_session_ids().length > 1;
- let shouldShowInMode = !Main.sessionMode.isLocked && !Main.sessionMode.isGreeter;
+ const allowLogout = !this._lockdownSettings.get_boolean(DISABLE_LOG_OUT_KEY);
+ const alwaysShow = global.settings.get_boolean(ALWAYS_SHOW_LOG_OUT_KEY);
+ const systemAccount = user.system_account;
+ const localAccount = user.local_account;
+ const multiUser = this._userManager.has_multiple_users;
+ const multiSession = Gdm.get_session_ids().length > 1;
+ const shouldShowInMode = !Main.sessionMode.isLocked && !Main.sessionMode.isGreeter;
- let visible = allowLogout && (alwaysShow || multiUser || multiSession || systemAccount || !localAccount) && shouldShowInMode;
+ const visible = allowLogout && (alwaysShow || multiUser || multiSession || systemAccount || !localAccount) && shouldShowInMode;
this._actions.get(LOGOUT_ACTION_ID).available = visible;
this.notify('can-logout');
if (!this._actions.get(LOCK_ORIENTATION_ACTION_ID).available)
throw new Error('The lock-orientation action is not available!');
- let locked = this._orientationSettings.get_boolean('orientation-lock');
+ const locked = this._orientationSettings.get_boolean('orientation-lock');
this._orientationSettings.set_boolean('orientation-lock', !locked);
}
* @returns {{url: string, pos: number}[]} the list of match objects, as described above
*/
export function findUrls(str) {
- let res = [], match;
+ const res = [];
+ let match;
while ((match = _urlRegexp.exec(str)))
res.push({url: match[2], pos: match.index + match[1].length});
return res;
*/
export function spawnCommandLine(commandLine) {
try {
- let [success_, argv] = GLib.shell_parse_argv(commandLine);
+ const [success_, argv] = GLib.shell_parse_argv(commandLine);
trySpawn(argv);
} catch (err) {
_handleSpawnError(commandLine, err);
null,
Gio.AppInfoCreateFlags.SUPPORTS_STARTUP_NOTIFICATION);
- let context = global.create_app_launch_context(0, -1);
+ const context = global.create_app_launch_context(0, -1);
app.launch([], context);
} catch (err) {
_handleSpawnError(argv[0], err);
// execute child process "foo" (No such file or directory)
// We are only interested in the part in the parentheses. (And
// we can't pattern match the text, since it gets localized.)
- let message = err.message.replace(/.*\((.+)\)/, '$1');
+ const message = err.message.replace(/.*\((.+)\)/, '$1');
throw new err.constructor({code: err.code, message});
} else {
throw err;
if (_desktopSettings == null)
_desktopSettings = new Gio.Settings({schema_id: 'org.gnome.desktop.interface'});
- let label = new St.Label({text: formatTime(date, params)});
+ const label = new St.Label({text: formatTime(date, params)});
_desktopSettings.connectObject(
'changed::clock-format', () => (label.text = formatTime(date, params)),
label);
* Returns the position at which it was inserted
*/
export function insertSorted(array, val, cmp) {
- let pos = lowerBound(array, val, cmp);
+ const pos = lowerBound(array, val, cmp);
array.splice(pos, 0, val);
return pos;
* 'alpha' and 'beta'. Returns NaN for unhandled 'versions'.
*/
function _GNOMEversionToNumber(version) {
- let ret = Number(version);
+ const ret = Number(version);
if (!isNaN(ret))
return ret;
if (version === 'alpha')
const v2Array = version2.split('.');
for (let i = 0; i < Math.max(v1Array.length, v2Array.length); i++) {
- let elemV1 = _GNOMEversionToNumber(v1Array[i] || '0');
- let elemV2 = _GNOMEversionToNumber(v2Array[i] || '0');
+ const elemV1 = _GNOMEversionToNumber(v1Array[i] || '0');
+ const elemV2 = _GNOMEversionToNumber(v2Array[i] || '0');
if (elemV1 < elemV2)
return -1;
if (elemV1 > elemV2)
if (!this._highlightRegex)
return GLib.markup_escape_text(text, -1);
- let escaped = [];
+ const escaped = [];
let lastMatchEnd = 0;
let match;
while ((match = this._highlightRegex.exec(text))) {
if (match.index > lastMatchEnd) {
- let unmatched = GLib.markup_escape_text(
+ const unmatched = GLib.markup_escape_text(
text.slice(lastMatchEnd, match.index), -1);
escaped.push(unmatched);
}
- let matched = GLib.markup_escape_text(match[0], -1);
+ const matched = GLib.markup_escape_text(match[0], -1);
escaped.push(`<b>${matched}</b>`);
lastMatchEnd = match.index + match[0].length;
}
- let unmatched = GLib.markup_escape_text(
+ const unmatched = GLib.markup_escape_text(
text.slice(lastMatchEnd), -1);
escaped.push(unmatched);
if (!this._locationValid)
return;
- let now = GLib.DateTime.new_now_local();
+ const now = GLib.DateTime.new_now_local();
// Update without loading indication if the current info is recent enough
if (this._weatherInfo.is_valid() &&
now.difference(this._lastUpdate) < UPDATE_THRESHOLD)
}
_onInstalledChanged() {
- let hadApp = this._weatherApp != null;
+ const hadApp = this._weatherApp != null;
this._weatherApp = this._appSystem.lookup_app(WEATHER_APP_ID);
- let haveApp = this._weatherApp != null;
+ const haveApp = this._weatherApp != null;
if (hadApp !== haveApp)
this.emit('changed');
- let neededAuth = this._needsAuth;
+ const neededAuth = this._needsAuth;
this._needsAuth = this._weatherApp === null ||
this._weatherApp.app_info.has_key('X-Flatpak');
}
_loadInfo() {
- let id = this._weatherInfo.connect('updated', () => {
+ const id = this._weatherInfo.connect('updated', () => {
this._weatherInfo.disconnect(id);
this._loading = false;
});
}
_onGClueLocationChanged() {
- let geoLocation = this._gclueService.location;
+ const geoLocation = this._gclueService.location;
// Provide empty name so GWeather sets location name
const location = GWeather.Location.new_detached('',
null,
}
_onAutomaticLocationChanged() {
- let useAutoLocation = this._settings.get_boolean('automatic-location');
+ const useAutoLocation = this._settings.get_boolean('automatic-location');
if (this._autoLocationRequested === useAutoLocation)
return;
}
_onLocationsChanged() {
- let locations = this._settings.get_value('locations').deepUnpack();
- let serialized = locations.shift();
+ const locations = this._settings.get_value('locations').deepUnpack();
+ const serialized = locations.shift();
let mostRecentLocation = null;
if (serialized)
}
_onPermStoreChanged(proxy, sender, params) {
- let [table, id, deleted_, data_, perms] = params;
+ const [table, id, deleted_, data_, perms] = params;
if (table !== 'gnome' || id !== 'geolocation')
return;
- let permission = perms['org.gnome.Weather'] || ['NONE'];
- let [accuracy] = permission;
+ const permission = perms['org.gnome.Weather'] || ['NONE'];
+ const [accuracy] = permission;
this._weatherAuthorized = accuracy !== 'NONE';
this._updateAutoLocation();
if (loadEvent === WebKit.LoadEvent.STARTED) {
this._secureMenu.setSecurityIcon(PortalHelperSecurityLevel.NOT_YET_DETERMINED);
} else if (loadEvent === WebKit.LoadEvent.COMMITTED) {
- let tlsInfo = this._webView.get_tls_info();
- let ret = tlsInfo[0];
- let flags = tlsInfo[2];
+ const tlsInfo = this._webView.get_tls_info();
+ const ret = tlsInfo[0];
+ const flags = tlsInfo[2];
if (ret && flags === 0)
this._secureMenu.setSecurityIcon(PortalHelperSecurityLevel.SECURE);
else
_onLoadFailedWithTlsErrors(view, failingURI, certificate, _errors) {
this._secureMenu.setSecurityIcon(PortalHelperSecurityLevel.INSECURE);
- let uri = GLib.Uri.parse(failingURI, HTTP_URI_FLAGS);
+ const uri = GLib.Uri.parse(failingURI, HTTP_URI_FLAGS);
this._networkSession.allow_tls_certificate_for_host(certificate, uri.get_host());
this._webView.load_uri(failingURI);
return true;
this._dbusImpl = Gio.DBusExportedObject.wrapJSObject(HelperDBusInterface, this);
this._queue = [];
- let action = new Gio.SimpleAction({name: 'quit'});
+ const action = new Gio.SimpleAction({name: 'quit'});
action.connect('activate', () => this.active_window.destroy());
this.add_action(action);
}
Close(connection) {
for (let i = 0; i < this._queue.length; i++) {
- let obj = this._queue[i];
+ const obj = this._queue[i];
if (obj.connection === connection) {
if (obj.window)
Refresh(connection) {
for (let i = 0; i < this._queue.length; i++) {
- let obj = this._queue[i];
+ const obj = this._queue[i];
if (obj.connection === connection) {
if (obj.window)
if (this._queue.length === 0)
return;
- let top = this._queue[0];
+ const top = this._queue[0];
if (top.window != null)
return;
this._requestExported = false;
this._request = Gio.DBusExportedObject.wrapJSObject(RequestIface, this);
- for (let option in options)
+ for (const option in options)
options[option] = options[option].deepUnpack();
this._buildLayout(title, description, body, options);
_buildLayout(title, description, body, options) {
// No support for non-modal system dialogs, so ignore the option
// let modal = options['modal'] || true;
- let denyLabel = options['deny_label'] || _('Deny');
- let grantLabel = options['grant_label'] || _('Allow');
- let choices = options['choices'] || [];
+ const denyLabel = options['deny_label'] || _('Deny');
+ const grantLabel = options['grant_label'] || _('Allow');
+ const choices = options['choices'] || [];
- let content = new Dialog.MessageDialogContent({title, description});
+ const content = new Dialog.MessageDialogContent({title, description});
this.contentLayout.add_child(content);
this._choices = new Map();
for (let i = 0; i < choices.length; i++) {
- let [id, name, opts, selected] = choices[i];
+ const [id, name, opts, selected] = choices[i];
if (opts.length > 0)
continue; // radio buttons, not implemented
- let check = new CheckBox.CheckBox();
+ const check = new CheckBox.CheckBox();
check.getLabelActor().text = name;
check.checked = selected === 'true';
content.add_child(check);
}
if (body) {
- let bodyLabel = new St.Label({
+ const bodyLabel = new St.Label({
text: body,
x_align: Clutter.ActorAlign.CENTER,
});
if (!super.open())
return false;
- let connection = this._invocation.get_connection();
+ const connection = this._invocation.get_connection();
this._requestExported = this._request.export(connection, this._handle);
return true;
}
this._request.unexport();
this._requestExported = false;
- let results = {};
+ const results = {};
if (response === DialogResponse.OK) {
- for (let [id, check] of this._choices) {
- let checked = check.checked ? 'true' : 'false';
+ for (const [id, check] of this._choices) {
+ const checked = check.checked ? 'true' : 'false';
results[id] = new GLib.Variant('s', checked);
}
}
return;
}
- let [handle, appId, parentWindow_, title, description, body, options] = params;
+ const [handle, appId, parentWindow_, title, description, body, options] = params;
// We probably want to use parentWindow and global.display.focus_window
// for this check in the future
if (appId && `${appId}.desktop` !== this._windowTracker.focus_app.id) {
return;
}
- let dialog = new AccessDialog(
+ const dialog = new AccessDialog(
invocation, handle, title, description, body, options);
dialog.open();
};
function _createWindowClone(window, size) {
- let [width, height] = window.get_size();
- let scale = Math.min(1.0, size / width, size / height);
+ const [width, height] = window.get_size();
+ const scale = Math.min(1.0, size / width, size / height);
return new Clutter.Clone({
source: window,
width: width * scale,
// We ignore skip-taskbar windows in switchers, but if they are attached
// to their parent, their position in the MRU list may be more appropriate
// than the parent; so start with the complete list ...
- let windows = global.display.get_tab_list(Meta.TabList.NORMAL_ALL, workspace);
+ const windows = global.display.get_tab_list(Meta.TabList.NORMAL_ALL, workspace);
// ... map windows to their parent where appropriate ...
return windows.map(w => {
return w.is_attached_dialog() ? w.get_transient_for() : w;
this.thumbnailsVisible = false;
- let apps = Shell.AppSystem.get_default().get_running();
+ const apps = Shell.AppSystem.get_default().get_running();
this._switcherList = new AppSwitcher(apps, this);
this._items = this._switcherList.icons;
// We try to avoid overflowing the screen so we base the resulting size on
// those calculations
if (this._thumbnails) {
- let childBox = this._switcherList.get_allocation_box();
- let primary = Main.layoutManager.primaryMonitor;
-
- let leftPadding = this.get_theme_node().get_padding(St.Side.LEFT);
- let rightPadding = this.get_theme_node().get_padding(St.Side.RIGHT);
- let bottomPadding = this.get_theme_node().get_padding(St.Side.BOTTOM);
- let hPadding = leftPadding + rightPadding;
-
- let icon = this._items[this._selectedIndex];
- let [posX] = icon.get_transformed_position();
- let thumbnailCenter = posX + icon.width / 2;
- let [, childNaturalWidth] = this._thumbnails.get_preferred_width(-1);
+ const childBox = this._switcherList.get_allocation_box();
+ const primary = Main.layoutManager.primaryMonitor;
+
+ const leftPadding = this.get_theme_node().get_padding(St.Side.LEFT);
+ const rightPadding = this.get_theme_node().get_padding(St.Side.RIGHT);
+ const bottomPadding = this.get_theme_node().get_padding(St.Side.BOTTOM);
+ const hPadding = leftPadding + rightPadding;
+
+ const icon = this._items[this._selectedIndex];
+ const [posX] = icon.get_transformed_position();
+ const thumbnailCenter = posX + icon.width / 2;
+ const [, childNaturalWidth] = this._thumbnails.get_preferred_width(-1);
childBox.x1 = Math.max(primary.x + leftPadding, Math.floor(thumbnailCenter - childNaturalWidth / 2));
if (childBox.x1 + childNaturalWidth > primary.x + primary.width - hPadding) {
- let offset = childBox.x1 + childNaturalWidth - primary.width + hPadding;
+ const offset = childBox.x1 + childNaturalWidth - primary.width + hPadding;
childBox.x1 = Math.max(primary.x + leftPadding, childBox.x1 - offset - hPadding);
}
- let spacing = this.get_theme_node().get_length('spacing');
+ const spacing = this.get_theme_node().get_length('spacing');
childBox.x2 = childBox.x1 + childNaturalWidth;
if (childBox.x2 > primary.x + primary.width - rightPadding)
childBox.x2 = primary.x + primary.width - rightPadding;
childBox.y1 = this._switcherList.allocation.y2 + spacing;
this._thumbnails.addClones(primary.y + primary.height - bottomPadding - childBox.y1);
- let [, childNaturalHeight] = this._thumbnails.get_preferred_height(-1);
+ const [, childNaturalHeight] = this._thumbnails.get_preferred_height(-1);
childBox.y2 = childBox.y1 + childNaturalHeight;
this._thumbnails.allocate(childBox);
}
}
_closeAppWindow(appIndex, windowIndex) {
- let appIcon = this._items[appIndex];
+ const appIcon = this._items[appIndex];
if (!appIcon)
return;
- let window = appIcon.cachedWindows[windowIndex];
+ const window = appIcon.cachedWindows[windowIndex];
if (!window)
return;
}
_quitApplication(appIndex) {
- let appIcon = this._items[appIndex];
+ const appIcon = this._items[appIndex];
if (!appIcon)
return;
else
this._select(this._selectedIndex, this._previousWindow());
} else {
- let nwindows = this._items[this._selectedIndex].cachedWindows.length;
+ const nwindows = this._items[this._selectedIndex].cachedWindows.length;
if (nwindows > 1)
this._select(this._selectedIndex, nwindows - 1);
else
else
this._select(this._selectedIndex, this._nextWindow());
} else {
- let nwindows = this._items[this._selectedIndex].cachedWindows.length;
+ const nwindows = this._items[this._selectedIndex].cachedWindows.length;
if (nwindows > 1)
this._select(this._selectedIndex, 0);
else
}
_windowActivated(thumbnailSwitcher, n) {
- let appIcon = this._items[this._selectedIndex];
+ const appIcon = this._items[this._selectedIndex];
Main.activateWindow(appIcon.cachedWindows[n]);
this.fadeAndDestroy();
}
}
_windowRemoved(thumbnailSwitcher, n) {
- let appIcon = this._items[this._selectedIndex];
+ const appIcon = this._items[this._selectedIndex];
if (!appIcon)
return;
if (appIcon.cachedWindows.length > 0) {
- let newIndex = Math.min(n, appIcon.cachedWindows.length - 1);
+ const newIndex = Math.min(n, appIcon.cachedWindows.length - 1);
this._select(this._selectedIndex, newIndex);
}
}
_finish(timestamp) {
- let appIcon = this._items[this._selectedIndex];
+ const appIcon = this._items[this._selectedIndex];
if (this._currentWindow < 0)
appIcon.app.activate_window(appIcon.cachedWindows[0], timestamp);
else if (appIcon.cachedWindows[this._currentWindow])
}
_destroyThumbnails() {
- let thumbnailsActor = this._thumbnails;
+ const thumbnailsActor = this._thumbnails;
this._thumbnails.ease({
opacity: 0,
duration: THUMBNAIL_FADE_TIME,
this._highlight = new St.Widget({style_class: 'cycler-highlight'});
this.add_child(this._highlight);
- let coordinate = Clutter.BindCoordinate.ALL;
- let constraint = new Clutter.BindConstraint({coordinate});
+ const coordinate = Clutter.BindCoordinate.ALL;
+ const constraint = new Clutter.BindConstraint({coordinate});
this._clone.bind_property('source', constraint, 'source', 0);
this.add_constraint(constraint);
}
_finish() {
- let window = this._items[this._selectedIndex];
- let ws = window.get_workspace();
- let workspaceManager = global.workspace_manager;
- let activeWs = workspaceManager.get_active_workspace();
+ const window = this._items[this._selectedIndex];
+ const ws = window.get_workspace();
+ const workspaceManager = global.workspace_manager;
+ const activeWs = workspaceManager.get_active_workspace();
if (window.minimized) {
Main.wm.skipNextEffect(window.get_compositor_private());
}
_getWindows() {
- let app = Shell.WindowTracker.get_default().focus_app;
+ const app = Shell.WindowTracker.get_default().focus_app;
let appWindows = app?.get_windows() ?? [];
if (this._settings.get_boolean('current-workspace-only')) {
super._init();
this._settings = new Gio.Settings({schema_id: 'org.gnome.shell.window-switcher'});
- let windows = this._getWindowList();
+ const windows = this._getWindowList();
- let mode = this._settings.get_enum('app-icon-mode');
+ const mode = this._settings.get_enum('app-icon-mode');
this._switcherList = new WindowSwitcher(windows, mode);
this._items = this._switcherList.icons;
}
let workspace = null;
if (this._settings.get_boolean('current-workspace-only')) {
- let workspaceManager = global.workspace_manager;
+ const workspaceManager = global.workspace_manager;
workspace = workspaceManager.get_active_workspace();
}
}
_closeWindow(windowIndex) {
- let windowIcon = this._items[windowIndex];
+ const windowIcon = this._items[windowIndex];
if (!windowIcon)
return;
let workspace = null;
if (this._settings.get_boolean('current-workspace-only')) {
- let workspaceManager = global.workspace_manager;
+ const workspaceManager = global.workspace_manager;
workspace = workspaceManager.get_active_workspace();
}
this.icons = [];
this._arrows = [];
- let windowTracker = Shell.WindowTracker.get_default();
- let settings = new Gio.Settings({schema_id: 'org.gnome.shell.app-switcher'});
+ const windowTracker = Shell.WindowTracker.get_default();
+ const settings = new Gio.Settings({schema_id: 'org.gnome.shell.app-switcher'});
let workspace = null;
if (settings.get_boolean('current-workspace-only')) {
- let workspaceManager = global.workspace_manager;
+ const workspaceManager = global.workspace_manager;
workspace = workspaceManager.get_active_workspace();
}
- let allWindows = getWindows(workspace);
+ const allWindows = getWindows(workspace);
// Construct the AppIcons, add to the popup
for (let i = 0; i < apps.length; i++) {
- let appIcon = new AppIcon(apps[i]);
+ const appIcon = new AppIcon(apps[i]);
// Cache the window list now; we don't handle dynamic changes here,
// and we don't want to be continually retrieving it
appIcon.cachedWindows = allWindows.filter(
while (this._items.length > 1 && this._items[j].style_class !== 'item-box')
j++;
- let themeNode = this._items[j].get_theme_node();
+ const themeNode = this._items[j].get_theme_node();
this._list.ensure_style();
- let iconPadding = themeNode.get_horizontal_padding();
- let iconBorder = themeNode.get_border_width(St.Side.LEFT) + themeNode.get_border_width(St.Side.RIGHT);
- let [, labelNaturalHeight] = this.icons[j].label.get_preferred_height(-1);
- let iconSpacing = labelNaturalHeight + iconPadding + iconBorder;
- let totalSpacing = this._list.spacing * (this._items.length - 1);
+ const iconPadding = themeNode.get_horizontal_padding();
+ const iconBorder = themeNode.get_border_width(St.Side.LEFT) + themeNode.get_border_width(St.Side.RIGHT);
+ const [, labelNaturalHeight] = this.icons[j].label.get_preferred_height(-1);
+ const iconSpacing = labelNaturalHeight + iconPadding + iconBorder;
+ const totalSpacing = this._list.spacing * (this._items.length - 1);
// We just assume the whole screen here due to weirdness happening with the passed width
- let primary = Main.layoutManager.primaryMonitor;
- let parentPadding = this.get_parent().get_theme_node().get_horizontal_padding();
- let availWidth = primary.width - parentPadding - this.get_theme_node().get_horizontal_padding();
+ const primary = Main.layoutManager.primaryMonitor;
+ const parentPadding = this.get_parent().get_theme_node().get_horizontal_padding();
+ const availWidth = primary.width - parentPadding - this.get_theme_node().get_horizontal_padding();
- let scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
- let iconSizes = baseIconSizes.map(s => s * scaleFactor);
+ const scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
+ const iconSizes = baseIconSizes.map(s => s * scaleFactor);
let iconSize = baseIconSizes[0];
if (this._items.length > 1) {
for (let i = 0; i < baseIconSizes.length; i++) {
iconSize = baseIconSizes[i];
- let height = iconSizes[i] + iconSpacing;
- let w = height * this._items.length + totalSpacing;
+ const height = iconSizes[i] + iconSpacing;
+ const w = height * this._items.length + totalSpacing;
if (w <= availWidth)
break;
}
// Allocate the main list items
super.vfunc_allocate(box);
- let contentBox = this.get_theme_node().get_content_box(box);
+ const contentBox = this.get_theme_node().get_content_box(box);
- let arrowHeight = Math.floor(this.get_theme_node().get_padding(St.Side.BOTTOM) / 3);
- let arrowWidth = arrowHeight * 2;
+ const arrowHeight = Math.floor(this.get_theme_node().get_padding(St.Side.BOTTOM) / 3);
+ const arrowWidth = arrowHeight * 2;
// Now allocate each arrow underneath its item
- let childBox = new Clutter.ActorBox();
+ const childBox = new Clutter.ActorBox();
for (let i = 0; i < this._items.length; i++) {
- let itemBox = this._items[i].allocation;
+ const itemBox = this._items[i].allocation;
childBox.x1 = contentBox.x1 + Math.floor(itemBox.x1 + (itemBox.x2 - itemBox.x1 - arrowWidth) / 2);
childBox.x2 = childBox.x1 + arrowWidth;
childBox.y1 = contentBox.y1 + itemBox.y2 + arrowHeight;
}
_enterItem(index) {
- let [x, y] = global.get_pointer();
- let pickedActor = global.stage.get_actor_at_pos(Clutter.PickMode.ALL, x, y);
+ const [x, y] = global.get_pointer();
+ const pickedActor = global.stage.get_actor_at_pos(Clutter.PickMode.ALL, x, y);
if (this._items[index].contains(pickedActor))
this._itemEntered(index);
}
_addIcon(appIcon) {
this.icons.push(appIcon);
- let item = this.addItem(appIcon, appIcon.label);
+ const item = this.addItem(appIcon, appIcon.label);
appIcon.app.connectObject('notify::state', app => {
if (app.state !== Shell.AppState.RUNNING)
this._removeIcon(app);
}, this);
- let arrow = new St.DrawingArea({style_class: 'switcher-arrow'});
+ const arrow = new St.DrawingArea({style_class: 'switcher-arrow'});
arrow.connect('repaint', () => SwitcherPopup.drawArrow(arrow, St.Side.BOTTOM));
this.add_child(arrow);
this._arrows.push(arrow);
}
_removeIcon(app) {
- let index = this.icons.findIndex(icon => {
+ const index = this.icons.findIndex(icon => {
return icon.app === app;
});
if (index === -1)
orientation: Clutter.Orientation.VERTICAL,
});
- let bin = new St.Bin({style_class: 'thumbnail'});
+ const bin = new St.Bin({style_class: 'thumbnail'});
box.add_child(bin);
this._thumbnailBins.push(bin);
return;
let totalPadding = this._items[0].get_theme_node().get_horizontal_padding() + this._items[0].get_theme_node().get_vertical_padding();
totalPadding += this.get_theme_node().get_horizontal_padding() + this.get_theme_node().get_vertical_padding();
- let [, labelNaturalHeight] = this._labels[0].get_preferred_height(-1);
- let spacing = this._items[0].child.get_theme_node().get_length('spacing');
- let scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
- let thumbnailSize = THUMBNAIL_DEFAULT_SIZE * scaleFactor;
+ const [, labelNaturalHeight] = this._labels[0].get_preferred_height(-1);
+ const spacing = this._items[0].child.get_theme_node().get_length('spacing');
+ const scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
+ const thumbnailSize = THUMBNAIL_DEFAULT_SIZE * scaleFactor;
availHeight = Math.min(availHeight - labelNaturalHeight - totalPadding - spacing, thumbnailSize);
let binHeight = availHeight + this._items[0].get_theme_node().get_vertical_padding() + this.get_theme_node().get_vertical_padding() - spacing;
binHeight = Math.min(thumbnailSize, binHeight);
for (let i = 0; i < this._thumbnailBins.length; i++) {
- let mutterWindow = this._windows[i].get_compositor_private();
+ const mutterWindow = this._windows[i].get_compositor_private();
if (!mutterWindow)
continue;
- let clone = _createWindowClone(mutterWindow, thumbnailSize);
+ const clone = _createWindowClone(mutterWindow, thumbnailSize);
this._thumbnailBins[i].set_height(binHeight);
this._thumbnailBins[i].child = clone;
}
_removeThumbnail(source, clone) {
- let index = this._clones.indexOf(clone);
+ const index = this._clones.indexOf(clone);
if (index === -1)
return;
this.add_child(this._icon);
this.label = new St.Label({text: window.get_title()});
- let tracker = Shell.WindowTracker.get_default();
+ const tracker = Shell.WindowTracker.get_default();
this.app = tracker.get_window_app(window);
- let mutterWindow = this.window.get_compositor_private();
+ const mutterWindow = this.window.get_compositor_private();
let size;
this._icon.destroy_all_children();
- let scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
+ const scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
switch (mode) {
case AppIconMode.THUMBNAIL_ONLY:
}
_createAppIcon(app, size) {
- let appIcon = app
+ const appIcon = app
? app.create_icon_texture(size)
: new St.Icon({icon_name: 'application-x-executable', icon_size: size});
appIcon.x_expand = appIcon.y_expand = true;
this.icons = [];
for (let i = 0; i < windows.length; i++) {
- let win = windows[i];
- let icon = new WindowIcon(win, mode);
+ const win = windows[i];
+ const icon = new WindowIcon(win, mode);
this.addItem(icon, icon.label);
this.icons.push(icon);
vfunc_get_preferred_height(forWidth) {
let [minHeight, natHeight] = super.vfunc_get_preferred_height(forWidth);
- let spacing = this.get_theme_node().get_padding(St.Side.BOTTOM);
- let [labelMin, labelNat] = this._label.get_preferred_height(-1);
+ const spacing = this.get_theme_node().get_padding(St.Side.BOTTOM);
+ const [labelMin, labelNat] = this._label.get_preferred_height(-1);
minHeight += labelMin + spacing;
natHeight += labelNat + spacing;
}
vfunc_allocate(box) {
- let themeNode = this.get_theme_node();
- let contentBox = themeNode.get_content_box(box);
+ const themeNode = this.get_theme_node();
+ const contentBox = themeNode.get_content_box(box);
const labelHeight = this._label.height;
const totalLabelHeight =
labelHeight + themeNode.get_padding(St.Side.BOTTOM);
}
_removeWindow(window) {
- let index = this.icons.findIndex(icon => {
+ const index = this.icons.findIndex(icon => {
return icon.window === window;
});
if (index === -1)
};
function _getCategories(info) {
- let categoriesStr = info.get_categories();
+ const categoriesStr = info.get_categories();
if (!categoriesStr)
return [];
return categoriesStr.split(';');
}
function _listsIntersect(a, b) {
- for (let itemA of a) {
+ for (const itemA of a) {
if (b.includes(itemA))
return true;
}
}
function _getFolderName(folder) {
- let name = folder.get_string('name');
+ const name = folder.get_string('name');
if (folder.get_boolean('translate')) {
- let translated = Shell.util_get_translated_folder_name(name);
+ const translated = Shell.util_get_translated_folder_name(name);
if (translated !== null)
return translated;
}
}
function _findBestFolderName(apps) {
- let appInfos = apps.map(app => app.get_app_info());
+ const appInfos = apps.map(app => app.get_app_info());
- let categoryCounter = {};
- let commonCategories = [];
+ const categoryCounter = {};
+ const commonCategories = [];
appInfos.reduce((categories, appInfo) => {
- for (let category of _getCategories(appInfo)) {
+ for (const category of _getCategories(appInfo)) {
if (!(category in categoryCounter))
categoryCounter[category] = 0;
return categories;
}, commonCategories);
- for (let category of commonCategories) {
+ for (const category of commonCategories) {
const directory = `${category}.directory`;
const translated = Shell.util_get_translated_folder_name(directory);
if (translated !== null)
}
_redisplay() {
- let oldApps = this._orderedItems.slice();
- let oldAppIds = oldApps.map(icon => icon.id);
+ const oldApps = this._orderedItems.slice();
+ const oldAppIds = oldApps.map(icon => icon.id);
- let newApps = this._loadApps().sort(this._compareItems.bind(this));
- let newAppIds = newApps.map(icon => icon.id);
+ const newApps = this._loadApps().sort(this._compareItems.bind(this));
+ const newAppIds = newApps.map(icon => icon.id);
- let addedApps = newApps.filter(icon => !oldAppIds.includes(icon.id));
- let removedApps = oldApps.filter(icon => !newAppIds.includes(icon.id));
+ const addedApps = newApps.filter(icon => !oldAppIds.includes(icon.id));
+ const removedApps = oldApps.filter(icon => !newAppIds.includes(icon.id));
// Remove old app icons
removedApps.forEach(icon => {
selectApp(id) {
if (this._items.has(id)) {
- let item = this._items.get(id);
+ const item = this._items.get(id);
if (item.mapped) {
this._selectAppInternal(id);
} else {
// Need to wait until the view is mapped
- let signalId = item.connect('notify::mapped', actor => {
+ const signalId = item.connect('notify::mapped', actor => {
if (actor.mapped) {
actor.disconnect(signalId);
this._selectAppInternal(id);
}
} else {
// Need to wait until the view is built
- let signalId = this.connect('view-loaded', () => {
+ const signalId = this.connect('view-loaded', () => {
this.disconnect(signalId);
this.selectApp(id);
});
this.remove_all_transitions();
this._grid.remove_all_transitions();
- let params = {
+ const params = {
duration: VIEWS_SWITCH_TIME,
mode: Clutter.AnimationMode.EASE_OUT_QUAD,
};
}
_loadApps() {
- let appIcons = [];
+ const appIcons = [];
this._appInfoList = Shell.AppSystem.get_default().get_installed().filter(appInfo => {
try {
appInfo.get_id(); // catch invalid file encodings
this._parentalControlsManager.shouldShowApp(appInfo);
});
- let apps = this._appInfoList.map(app => app.get_id());
+ const apps = this._appInfoList.map(app => app.get_id());
- let appSys = Shell.AppSystem.get_default();
+ const appSys = Shell.AppSystem.get_default();
const appsInsideFolders = new Set();
this._folderIcons = [];
- let folders = this._folderSettings.get_strv('folder-children');
+ const folders = this._folderSettings.get_strv('folder-children');
folders.forEach(id => {
- let path = `${this._folderSettings.path}folders/${id}/`;
+ const path = `${this._folderSettings.path}folders/${id}/`;
let icon = this._items.get(id);
if (!icon) {
icon = new FolderIcon(id, path, this);
let icon = this._items.get(appId);
if (!icon) {
- let app = appSys.lookup_app(appId);
+ const app = appSys.lookup_app(appId);
icon = new AppIcon(app, {isDraggable});
}
this._savePages();
- let view = _getViewFromIcon(source);
+ const view = _getViewFromIcon(source);
if (view instanceof FolderView)
view.removeApp(source.app);
}
createFolder(apps) {
- let newFolderId = GLib.uuid_string_random();
+ const newFolderId = GLib.uuid_string_random();
- let folders = this._folderSettings.get_strv('folder-children');
+ const folders = this._folderSettings.get_strv('folder-children');
folders.push(newFolderId);
this._folderSettings.set_strv('folder-children', folders);
// Create the new folder
- let newFolderPath = this._folderSettings.path.concat('folders/', newFolderId, '/');
+ const newFolderPath = this._folderSettings.path.concat('folders/', newFolderId, '/');
let newFolderSettings;
try {
newFolderSettings = new Gio.Settings({
return counter;
}, 0);
- let appItems = apps.map(id => this._items.get(id).app);
+ const appItems = apps.map(id => this._items.get(id).app);
let folderName = _findBestFolderName(appItems);
if (!folderName)
folderName = _('Unnamed Folder');
getResultMetas(apps) {
const {scaleFactor} = St.ThemeContext.get_for_stage(global.stage);
- let metas = [];
- for (let id of apps) {
+ const metas = [];
+ for (const id of apps) {
if (id.endsWith('.desktop')) {
- let app = this._appSys.lookup_app(id);
+ const app = this._appSys.lookup_app(id);
metas.push({
id: app.get_id(),
createIcon: size => app.create_icon_texture(size),
});
} else {
- let name = this._systemActions.getName(id);
- let iconName = this._systemActions.getIconName(id);
+ const name = this._systemActions.getName(id);
+ const iconName = this._systemActions.getIconName(id);
const createIcon = size => new St.Icon({
icon_name: iconName,
// results can be filtered correctly.
if (!this._parentalControlsManager.initialized) {
return new Promise(resolve => {
- let initializedId = this._parentalControlsManager.connect('app-filter-changed', async () => {
+ const initializedId = this._parentalControlsManager.connect('app-filter-changed', async () => {
if (this._parentalControlsManager.initialized) {
this._parentalControlsManager.disconnect(initializedId);
resolve(await this.getInitialResultSet(terms, cancellable));
});
}
- let query = terms.join(' ');
- let groups = Shell.AppSystem.search(query);
- let usage = Shell.AppUsage.get_default();
+ const query = terms.join(' ');
+ const groups = Shell.AppSystem.search(query);
+ const usage = Shell.AppUsage.get_default();
let results = [];
groups.forEach(group => {
row_homogeneous: true,
column_homogeneous: true,
});
- let icon = new St.Widget({
+ const icon = new St.Widget({
layout_manager: layout,
x_align: Clutter.ActorAlign.CENTER,
style: `width: ${size}px; height: ${size}px;`,
});
- let subSize = Math.floor(FOLDER_SUBICON_FRACTION * size);
+ const subSize = Math.floor(FOLDER_SUBICON_FRACTION * size);
- let numItems = this._orderedItems.length;
- let rtl = icon.get_text_direction() === Clutter.TextDirection.RTL;
+ const numItems = this._orderedItems.length;
+ const rtl = icon.get_text_direction() === Clutter.TextDirection.RTL;
for (let i = 0; i < 4; i++) {
const style = `width: ${subSize}px; height: ${subSize}px;`;
- let bin = new St.Bin({style});
+ const bin = new St.Bin({style});
if (i < numItems)
bin.child = this._orderedItems[i].app.create_icon_texture(subSize);
layout.attach(bin, rtl ? (i + 1) % 2 : i % 2, Math.floor(i / 2), 1, 1);
const folderCategories = this._folder.get_strv('categories');
const appInfos = this._parentView.getAppInfos();
appInfos.forEach(appInfo => {
- let appCategories = _getCategories(appInfo);
+ const appCategories = _getCategories(appInfo);
if (!_listsIntersect(folderCategories, appCategories))
return;
addAppId(appInfo.get_id());
});
- let items = [];
+ const items = [];
this._apps.forEach(app => {
let icon = this._items.get(app.get_id());
if (!icon)
}
addApp(app) {
- let folderApps = this._folder.get_strv('apps');
+ const folderApps = this._folder.get_strv('apps');
folderApps.push(app.id);
this._folder.set_strv('apps', folderApps);
// Also remove from 'excluded-apps' if the app id is listed
// there. This is only possible on categories-based folders.
- let excludedApps = this._folder.get_strv('excluded-apps');
- let index = excludedApps.indexOf(app.id);
+ const excludedApps = this._folder.get_strv('excluded-apps');
+ const index = excludedApps.indexOf(app.id);
if (index >= 0) {
excludedApps.splice(index, 1);
this._folder.set_strv('excluded-apps', excludedApps);
}
removeApp(app) {
- let folderApps = this._folder.get_strv('apps');
- let index = folderApps.indexOf(app.id);
+ const folderApps = this._folder.get_strv('apps');
+ const index = folderApps.indexOf(app.id);
if (index >= 0)
folderApps.splice(index, 1);
this._deletingFolder = true;
// Resetting all keys deletes the relocatable schema
- let keys = this._folder.settings_schema.list_keys();
+ const keys = this._folder.settings_schema.list_keys();
for (const key of keys)
this._folder.reset(key);
- let settings = new Gio.Settings({schema_id: 'org.gnome.desktop.app-folders'});
- let folders = settings.get_strv('folder-children');
+ const settings = new Gio.Settings({schema_id: 'org.gnome.desktop.app-folders'});
+ const folders = settings.get_strv('folder-children');
folders.splice(folders.indexOf(this._id), 1);
settings.set_strv('folder-children', folders);
if (!(source instanceof AppIcon))
return false;
- let view = _getViewFromIcon(source);
+ const view = _getViewFromIcon(source);
if (!view || !(view instanceof AppDisplay))
return false;
}
_updateName() {
- let name = _getFolderName(this._folder);
+ const name = _getFolderName(this._folder);
if (this.name === name)
return;
this._viewBox.add_child(this._entryBox);
// Empty actor to center the title
- let ghostButton = new Clutter.Actor();
+ const ghostButton = new Clutter.Actor();
this._entryBox.add_child(ghostButton);
- let stack = new Shell.Stack({
+ const stack = new Shell.Stack({
x_expand: true,
x_align: Clutter.ActorAlign.CENTER,
});
}
_syncFolderName() {
- let newName = _getFolderName(this._folder);
+ const newName = _getFolderName(this._folder);
this._folderNameLabel.text = newName;
this._entry.text = newName;
}
_maybeUpdateFolderName() {
- let folderName = _getFolderName(this._folder);
- let newFolderName = this._entry.text.trim();
+ const folderName = _getFolderName(this._folder);
+ const newFolderName = this._entry.text.trim();
if (newFolderName.length === 0 || newFolderName === folderName)
return;
}
_zoomAndFadeIn() {
- let [sourceX, sourceY] =
+ const [sourceX, sourceY] =
this._source.get_transformed_position();
- let [dialogX, dialogY] =
+ const [dialogX, dialogY] =
this.child.get_transformed_position();
this.child.set({
return;
}
- let [sourceX, sourceY] =
+ const [sourceX, sourceY] =
this._source.get_transformed_position();
- let [dialogX, dialogY] =
+ const [dialogX, dialogY] =
this.child.get_transformed_position();
this.ease({
}
activate(button) {
- let event = Clutter.get_current_event();
- let modifiers = event ? event.get_state() : 0;
- let isMiddleButton = button && button === Clutter.BUTTON_MIDDLE;
- let isCtrlPressed = (modifiers & Clutter.ModifierType.CONTROL_MASK) !== 0;
- let openNewWindow = this.app.can_open_new_window() &&
+ const event = Clutter.get_current_event();
+ const modifiers = event ? event.get_state() : 0;
+ const isMiddleButton = button && button === Clutter.BUTTON_MIDDLE;
+ const isCtrlPressed = (modifiers & Clutter.ModifierType.CONTROL_MASK) !== 0;
+ const openNewWindow = this.app.can_open_new_window() &&
this.app.state === Shell.AppState.RUNNING &&
(isCtrlPressed || isMiddleButton);
}
_canAccept(source) {
- let view = _getViewFromIcon(source);
+ const view = _getViewFromIcon(source);
return source !== this &&
(source instanceof this.constructor) &&
if (!accepted)
return false;
- let view = _getViewFromIcon(this);
- let apps = [this.id, source.id];
+ const view = _getViewFromIcon(this);
+ const apps = [this.id, source.id];
return view?.createFolder(apps);
}
}
reload() {
- let ids = global.settings.get_strv(this.FAVORITE_APPS_KEY);
- let appSys = Shell.AppSystem.get_default();
- let apps = ids.map(id => appSys.lookup_app(id))
+ const ids = global.settings.get_strv(this.FAVORITE_APPS_KEY);
+ const appSys = Shell.AppSystem.get_default();
+ const apps = ids.map(id => appSys.lookup_app(id))
.filter(app => app !== null && this._parentalControlsManager.shouldShowApp(app.app_info));
this._favorites = {};
for (let i = 0; i < apps.length; i++) {
- let app = apps[i];
+ const app = apps[i];
this._favorites[app.get_id()] = app;
}
}
_getIds() {
- let ret = [];
- for (let id in this._favorites)
+ const ret = [];
+ for (const id in this._favorites)
ret.push(id);
return ret;
}
}
getFavorites() {
- let ret = [];
- for (let id in this._favorites)
+ const ret = [];
+ for (const id in this._favorites)
ret.push(this._favorites[id]);
return ret;
}
if (appId in this._favorites)
return false;
- let app = Shell.AppSystem.get_default().lookup_app(appId);
+ const app = Shell.AppSystem.get_default().lookup_app(appId);
if (!app)
return false;
if (!this._parentalControlsManager.shouldShowApp(app.app_info))
return false;
- let ids = this._getIds();
+ const ids = this._getIds();
if (pos === -1)
ids.push(appId);
else
if (!(appId in this._favorites))
return false;
- let ids = this._getIds().filter(id => id !== appId);
+ const ids = this._getIds().filter(id => id !== appId);
global.settings.set_strv(this.FAVORITE_APPS_KEY, ids);
return true;
}
removeFavorite(appId) {
- let ids = this._getIds();
- let pos = ids.indexOf(appId);
+ const ids = this._getIds();
+ const pos = ids.indexOf(appId);
- let app = this._favorites[appId];
+ const app = this._favorites[appId];
if (!this._removeFavorite(appId))
return;
}
_buildLayout() {
- let content = new Dialog.MessageDialogContent({
+ const content = new Dialog.MessageDialogContent({
title: _('Select Audio Device'),
});
}
_openSettings() {
- let desktopFile = 'gnome-sound-panel.desktop';
- let app = Shell.AppSystem.get_default().lookup_app(desktopFile);
+ const desktopFile = 'gnome-sound-panel.desktop';
+ const app = Shell.AppSystem.get_default().lookup_app(desktopFile);
if (!app) {
log(`Settings panel for desktop file ${desktopFile} could not be loaded!`);
}
_onDeviceSelected(dialog, device) {
- let connection = this._dbusImpl.get_connection();
- let info = this._dbusImpl.get_info();
+ const connection = this._dbusImpl.get_connection();
+ const info = this._dbusImpl.get_info();
const deviceName = Object.keys(AudioDevice)
.filter(dev => AudioDevice[dev] === device)[0].toLowerCase();
connection.emit_signal(
return;
}
- let [deviceNames] = params;
+ const [deviceNames] = params;
let devices = 0;
deviceNames.forEach(n => (devices |= AudioDevice[n.toUpperCase()]));
}
monitorFile(file) {
- let key = file.hash();
+ const key = file.hash();
if (this._fileMonitors[key])
return;
- let monitor = file.monitor(Gio.FileMonitorFlags.NONE, null);
+ const monitor = file.monitor(Gio.FileMonitorFlags.NONE, null);
monitor.connect('changed',
(obj, theFile, otherFile, eventType) => {
// Ignore CHANGED and CREATED events, since in both cases
let animation = this._animations[params.settingsSchema];
if (animation && _fileEqual0(animation.file, params.file)) {
if (params.onLoaded) {
- let id = GLib.idle_add(GLib.PRIORITY_DEFAULT, () => {
+ const id = GLib.idle_add(GLib.PRIORITY_DEFAULT, () => {
params.onLoaded(this._animations[params.settingsSchema]);
return GLib.SOURCE_REMOVE;
});
this._animations[params.settingsSchema] = animation;
if (params.onLoaded) {
- let id = GLib.idle_add(GLib.PRIORITY_DEFAULT, () => {
+ const id = GLib.idle_add(GLib.PRIORITY_DEFAULT, () => {
params.onLoaded(this._animations[params.settingsSchema]);
return GLib.SOURCE_REMOVE;
});
releaseBackgroundSource(settingsSchema) {
if (settingsSchema in this._backgroundSources) {
- let source = this._backgroundSources[settingsSchema];
+ const source = this._backgroundSources[settingsSchema];
source._useCount--;
if (source._useCount === 0) {
delete this._backgroundSources[settingsSchema];
this._loadAnimation(this._animation.file);
}, this);
- let loginManager = LoginManager.getLoginManager();
+ const loginManager = LoginManager.getLoginManager();
loginManager.connectObject('prepare-for-sleep',
(lm, aboutToSuspend) => {
if (aboutToSuspend)
this._removeAnimationTimeout();
let i;
- let keys = Object.keys(this._fileWatches);
+ const keys = Object.keys(this._fileWatches);
for (i = 0; i < keys.length; i++)
this._cache.disconnect(this._fileWatches[keys[i]]);
if (this._cancellable?.is_cancelled())
return;
- let id = GLib.idle_add(GLib.PRIORITY_DEFAULT, () => {
+ const id = GLib.idle_add(GLib.PRIORITY_DEFAULT, () => {
this.emit('loaded');
return GLib.SOURCE_REMOVE;
});
}
_loadPattern() {
- let colorString, res_, color, secondColor;
-
- colorString = this._settings.get_string(PRIMARY_COLOR_KEY);
- [res_, color] = Cogl.Color.from_string(colorString);
+ let colorString = this._settings.get_string(PRIMARY_COLOR_KEY);
+ const [, color] = Cogl.Color.from_string(colorString);
colorString = this._settings.get_string(SECONDARY_COLOR_KEY);
- [res_, secondColor] = Cogl.Color.from_string(colorString);
+ const [, secondColor] = Cogl.Color.from_string(colorString);
- let shadingType = this._settings.get_enum(COLOR_SHADING_TYPE_KEY);
+ const shadingType = this._settings.get_enum(COLOR_SHADING_TYPE_KEY);
if (shadingType === GDesktopEnums.BackgroundShading.SOLID)
this.set_color(color);
}
_watchFile(file) {
- let key = file.hash();
+ const key = file.hash();
if (this._fileWatches[key])
return;
this._cache.monitorFile(file);
- let signalId = this._cache.connect('file-changed',
+ const signalId = this._cache.connect('file-changed',
(cache, changedFile) => {
if (changedFile.equal(file)) {
- let imageCache = Meta.BackgroundImageCache.get_default();
+ const imageCache = Meta.BackgroundImageCache.get_default();
imageCache.purge(changedFile);
this._emitChangedSignal();
}
this._updateAnimationTimeoutId = 0;
this._animation.update(this._layoutManager.monitors[this._monitorIndex]);
- let files = this._animation.keyFrameFiles;
+ const files = this._animation.keyFrameFiles;
- let finish = () => {
+ const finish = () => {
this._setLoaded();
if (files.length > 1) {
this.set_blend(files[0], files[1],
this._queueUpdateAnimation();
};
- let cache = Meta.BackgroundImageCache.get_default();
+ const cache = Meta.BackgroundImageCache.get_default();
let numPendingImages = files.length;
for (let i = 0; i < files.length; i++) {
this._watchFile(files[i]);
- let image = cache.load(files[i]);
+ const image = cache.load(files[i]);
if (image.is_loaded()) {
numPendingImages--;
if (numPendingImages === 0)
finish();
} else {
// eslint-disable-next-line no-loop-func
- let id = image.connect('loaded', () => {
+ const id = image.connect('loaded', () => {
image.disconnect(id);
numPendingImages--;
if (numPendingImages === 0)
if (!this._animation.transitionDuration)
return;
- let nSteps = 255 / ANIMATION_OPACITY_STEP_INCREMENT;
- let timePerStep = (this._animation.transitionDuration * 1000) / nSteps;
+ const nSteps = 255 / ANIMATION_OPACITY_STEP_INCREMENT;
+ const timePerStep = (this._animation.transitionDuration * 1000) / nSteps;
- let interval = Math.max(
+ const interval = Math.max(
ANIMATION_MIN_WAKEUP_INTERVAL * 1000,
timePerStep);
this.set_file(file, this._style);
this._watchFile(file);
- let cache = Meta.BackgroundImageCache.get_default();
- let image = cache.load(file);
+ const cache = Meta.BackgroundImageCache.get_default();
+ const image = cache.load(file);
if (image.is_loaded()) {
this._setLoaded();
} else {
- let id = image.connect('loaded', () => {
+ const id = image.connect('loaded', () => {
this._setLoaded();
image.disconnect(id);
});
});
this.content.background = _systemBackground;
- let id = GLib.idle_add(GLib.PRIORITY_DEFAULT, () => {
+ const id = GLib.idle_add(GLib.PRIORITY_DEFAULT, () => {
this.emit('loaded');
return GLib.SOURCE_REMOVE;
});
}
_onMonitorsChanged() {
- for (let monitorIndex in this._backgrounds) {
- let background = this._backgrounds[monitorIndex];
+ for (const monitorIndex in this._backgrounds) {
+ const background = this._backgrounds[monitorIndex];
if (monitorIndex < this._layoutManager.monitors.length) {
background.updateResolution();
monitorIndex = 0;
if (!(monitorIndex in this._backgrounds)) {
- let background = new Background({
+ const background = new Background({
monitorIndex,
layoutManager: this._layoutManager,
settings: this._settings,
const monitorManager = global.backend.get_monitor_manager();
monitorManager.disconnect(this._monitorsChangedId);
- for (let monitorIndex in this._backgrounds) {
- let background = this._backgrounds[monitorIndex];
+ for (const monitorIndex in this._backgrounds) {
+ const background = this._backgrounds[monitorIndex];
background.disconnect(background._changedId);
background.destroy();
}
if (this.get_num_slides() < 1)
return;
- let [progress, duration, isFixed_, filename1, filename2] =
+ const [progress, duration, isFixed_, filename1, filename2] =
this.get_current_slide(monitor.width, monitor.height);
this.transitionDuration = duration;
useContentSize: true,
});
- let cache = getBackgroundCache();
+ const cache = getBackgroundCache();
this._settingsSchema = params.settingsSchema;
this._backgroundSource = cache.getBackgroundSource(params.layoutManager, params.settingsSchema);
}
destroy() {
- let cache = getBackgroundCache();
+ const cache = getBackgroundCache();
cache.releaseBackgroundSource(this._settingsSchema);
this._backgroundSource = null;
}
_swapBackgroundActor() {
- let oldBackgroundActor = this.backgroundActor;
+ const oldBackgroundActor = this.backgroundActor;
this.backgroundActor = this._newBackgroundActor;
this._newBackgroundActor = null;
this.emit('changed');
this._newBackgroundActor = null;
}
- let newBackgroundActor = this._createBackgroundActor();
+ const newBackgroundActor = this._createBackgroundActor();
const oldContent = this.backgroundActor.content;
const newContent = newBackgroundActor.content;
}
_createBackgroundActor() {
- let background = this._backgroundSource.getBackground(this._monitorIndex);
- let backgroundActor = new Meta.BackgroundActor({
+ const background = this._backgroundSource.getBackground(this._monitorIndex);
+ const backgroundActor = new Meta.BackgroundActor({
meta_display: global.display,
monitor: this._monitorIndex,
request_mode: this._useContentSize
this._container.add_child(backgroundActor);
if (this._controlPosition) {
- let monitor = this._layoutManager.monitors[this._monitorIndex];
+ const monitor = this._layoutManager.monitors[this._monitorIndex];
backgroundActor.set_position(monitor.x, monitor.y);
this._container.set_child_below_sibling(backgroundActor, null);
}
}
vfunc_repaint() {
- let cr = this.get_context();
- let themeNode = this.get_theme_node();
- let [width, height] = this.get_surface_size();
+ const cr = this.get_context();
+ const themeNode = this.get_theme_node();
+ const [width, height] = this.get_surface_size();
const rtl = this.get_text_direction() === Clutter.TextDirection.RTL;
const barLevelBorderRadius = Math.min(width, this._barLevelHeight) / 2;
- let fgColor = themeNode.get_foreground_color();
+ const fgColor = themeNode.get_foreground_color();
const TAU = Math.PI * 2;
let overdriveRatio = this._overdriveStart / this._maxValue;
if (rtl)
overdriveRatio = 1 - overdriveRatio;
- let overdriveSeparatorX = barLevelBorderRadius + (width - 2 * barLevelBorderRadius) * overdriveRatio;
+ const overdriveSeparatorX = barLevelBorderRadius + (width - 2 * barLevelBorderRadius) * overdriveRatio;
- let overdriveActive = this._overdriveStart !== this._maxValue;
+ const overdriveActive = this._overdriveStart !== this._maxValue;
const overdriveSeparatorWidth = overdriveActive
? this._overdriveSeparatorWidth : 0;
event.type() === Clutter.EventType.LEAVE)
return Clutter.EVENT_PROPAGATE;
- let mute = event.type() === Clutter.EventType.KEY_PRESS ||
+ const mute = event.type() === Clutter.EventType.KEY_PRESS ||
event.type() === Clutter.EventType.KEY_RELEASE
? this._muteKeys : this._muteInput;
}
open(animate, onComplete) {
- let themeNode = this.get_theme_node();
- let rise = themeNode.get_length('-arrow-rise');
- let animationTime = animate & PopupAnimation.FULL ? POPUP_ANIMATION_TIME : 0;
+ const themeNode = this.get_theme_node();
+ const rise = themeNode.get_length('-arrow-rise');
+ const animationTime = animate & PopupAnimation.FULL ? POPUP_ANIMATION_TIME : 0;
if (animate & PopupAnimation.FADE)
this.opacity = 0;
let translationY = 0;
let scaleX = 1;
let scaleY = 1;
- let themeNode = this.get_theme_node();
- let rise = themeNode.get_length('-arrow-rise');
- let fade = animate & PopupAnimation.FADE;
- let animationTime = animate & PopupAnimation.FULL ? POPUP_ANIMATION_TIME : 0;
+ const themeNode = this.get_theme_node();
+ const rise = themeNode.get_length('-arrow-rise');
+ const fade = animate & PopupAnimation.FADE;
+ const animationTime = animate & PopupAnimation.FULL ? POPUP_ANIMATION_TIME : 0;
if (animate & PopupAnimation.SLIDE) {
scaleX = 0.96;
}
_adjustAllocationForArrow(isWidth, minSize, natSize) {
- let themeNode = this.get_theme_node();
- let borderWidth = themeNode.get_length('-arrow-border-width');
+ const themeNode = this.get_theme_node();
+ const borderWidth = themeNode.get_length('-arrow-border-width');
minSize += borderWidth * 2;
natSize += borderWidth * 2;
if ((!isWidth && (this._arrowSide === St.Side.TOP || this._arrowSide === St.Side.BOTTOM)) ||
(isWidth && (this._arrowSide === St.Side.LEFT || this._arrowSide === St.Side.RIGHT))) {
- let rise = themeNode.get_length('-arrow-rise');
+ const rise = themeNode.get_length('-arrow-rise');
minSize += rise;
natSize += rise;
}
}
vfunc_get_preferred_width(forHeight) {
- let themeNode = this.get_theme_node();
+ const themeNode = this.get_theme_node();
forHeight = themeNode.adjust_for_height(forHeight);
let width = this.bin.get_preferred_width(forHeight);
}
vfunc_get_preferred_height(forWidth) {
- let themeNode = this.get_theme_node();
- let borderWidth = themeNode.get_length('-arrow-border-width');
+ const themeNode = this.get_theme_node();
+ const borderWidth = themeNode.get_length('-arrow-border-width');
forWidth = themeNode.adjust_for_width(forWidth);
let height = this.bin.get_preferred_height(forWidth - 2 * borderWidth);
this.set_allocation(box);
- let themeNode = this.get_theme_node();
- let borderWidth = themeNode.get_length('-arrow-border-width');
- let rise = themeNode.get_length('-arrow-rise');
- let childBox = new Clutter.ActorBox();
- let [availWidth, availHeight] = themeNode.get_content_box(box).get_size();
+ const themeNode = this.get_theme_node();
+ const borderWidth = themeNode.get_length('-arrow-border-width');
+ const rise = themeNode.get_length('-arrow-rise');
+ const childBox = new Clutter.ActorBox();
+ const [availWidth, availHeight] = themeNode.get_content_box(box).get_size();
childBox.x1 = 0;
childBox.y1 = 0;
}
_drawBorder(area) {
- let themeNode = this.get_theme_node();
+ const themeNode = this.get_theme_node();
if (this._arrowActor) {
- let [sourceX, sourceY] = this._arrowActor.get_transformed_position();
- let [sourceWidth, sourceHeight] = this._arrowActor.get_transformed_size();
- let [absX, absY] = this.get_transformed_position();
+ const [sourceX, sourceY] = this._arrowActor.get_transformed_position();
+ const [sourceWidth, sourceHeight] = this._arrowActor.get_transformed_size();
+ const [absX, absY] = this.get_transformed_position();
if (this._arrowSide === St.Side.TOP ||
this._arrowSide === St.Side.BOTTOM)
this._arrowOrigin = sourceY - absY + sourceHeight / 2;
}
- let borderWidth = themeNode.get_length('-arrow-border-width');
- let base = themeNode.get_length('-arrow-base');
- let rise = themeNode.get_length('-arrow-rise');
- let borderRadius = themeNode.get_length('-arrow-border-radius');
+ const borderWidth = themeNode.get_length('-arrow-border-width');
+ const base = themeNode.get_length('-arrow-base');
+ const rise = themeNode.get_length('-arrow-rise');
+ const borderRadius = themeNode.get_length('-arrow-border-radius');
- let halfBorder = borderWidth / 2;
- let halfBase = Math.floor(base / 2);
+ const halfBorder = borderWidth / 2;
+ const halfBase = Math.floor(base / 2);
- let [width, height] = area.get_surface_size();
+ const [width, height] = area.get_surface_size();
let [boxWidth, boxHeight] = [width, height];
if (this._arrowSide === St.Side.TOP || this._arrowSide === St.Side.BOTTOM)
boxHeight -= rise;
else
boxWidth -= rise;
- let cr = area.get_context();
+ const cr = area.get_context();
// Translate so that box goes from 0,0 to boxWidth,boxHeight,
// with the arrow poking out of that
else if (this._arrowSide === St.Side.LEFT)
cr.translate(rise, 0);
- let [x1, y1] = [halfBorder, halfBorder];
- let [x2, y2] = [boxWidth - halfBorder, boxHeight - halfBorder];
+ const [x1, y1] = [halfBorder, halfBorder];
+ const [x2, y2] = [boxWidth - halfBorder, boxHeight - halfBorder];
let skipTopLeft = false;
let skipTopRight = false;
}
if (borderWidth > 0) {
- let borderColor = themeNode.get_color('-arrow-border-color');
+ const borderColor = themeNode.get_color('-arrow-border-color');
cr.setSourceColor(borderColor);
cr.setLineWidth(borderWidth);
cr.stroke();
}
_reposition(allocationBox) {
- let sourceActor = this._sourceActor;
+ const sourceActor = this._sourceActor;
let alignment = this._arrowAlignment;
- let monitorIndex = Main.layoutManager.findIndexForActor(sourceActor);
+ const monitorIndex = Main.layoutManager.findIndexForActor(sourceActor);
this._sourceExtents = sourceActor.get_transformed_extents();
this._workArea = Main.layoutManager.getWorkAreaForMonitor(monitorIndex);
x2: sourceAllocation.get_width(),
y2: sourceAllocation.get_height(),
});
- let sourceTopLeft = this._sourceExtents.get_top_left();
- let sourceBottomRight = this._sourceExtents.get_bottom_right();
- let sourceCenterX = sourceTopLeft.x + sourceContentBox.x1 + (sourceContentBox.x2 - sourceContentBox.x1) * this._sourceAlignment;
- let sourceCenterY = sourceTopLeft.y + sourceContentBox.y1 + (sourceContentBox.y2 - sourceContentBox.y1) * this._sourceAlignment;
- let [, , natWidth, natHeight] = this.get_preferred_size();
+ const sourceTopLeft = this._sourceExtents.get_top_left();
+ const sourceBottomRight = this._sourceExtents.get_bottom_right();
+ const sourceCenterX = sourceTopLeft.x + sourceContentBox.x1 + (sourceContentBox.x2 - sourceContentBox.x1) * this._sourceAlignment;
+ const sourceCenterY = sourceTopLeft.y + sourceContentBox.y1 + (sourceContentBox.y2 - sourceContentBox.y1) * this._sourceAlignment;
+ const [, , natWidth, natHeight] = this.get_preferred_size();
// We also want to keep it onscreen, and separated from the
// edge by the same distance as the main part of the box is
// separated from its sourceActor
- let workarea = this._workArea;
- let themeNode = this.get_theme_node();
- let borderWidth = themeNode.get_length('-arrow-border-width');
- let arrowBase = themeNode.get_length('-arrow-base');
- let borderRadius = themeNode.get_length('-arrow-border-radius');
- let margin = 4 * borderRadius + borderWidth + arrowBase;
+ const workarea = this._workArea;
+ const themeNode = this.get_theme_node();
+ const borderWidth = themeNode.get_length('-arrow-border-width');
+ const arrowBase = themeNode.get_length('-arrow-base');
+ const borderRadius = themeNode.get_length('-arrow-border-radius');
+ const margin = 4 * borderRadius + borderWidth + arrowBase;
- let gap = themeNode.get_length('-boxpointer-gap');
- let padding = themeNode.get_length('-arrow-rise');
+ const gap = themeNode.get_length('-boxpointer-gap');
+ const padding = themeNode.get_length('-arrow-rise');
let resX, resY;
// of the box to maintain the arrow's accuracy.
let arrowOrigin;
- let halfBase = Math.floor(arrowBase / 2);
- let halfBorder = borderWidth / 2;
- let halfMargin = margin / 2;
- let [x1, y1] = [halfBorder, halfBorder];
- let [x2, y2] = [natWidth - halfBorder, natHeight - halfBorder];
+ const halfBase = Math.floor(arrowBase / 2);
+ const halfBorder = borderWidth / 2;
+ const halfMargin = margin / 2;
+ const [x1, y1] = [halfBorder, halfBorder];
+ const [x2, y2] = [natWidth - halfBorder, natHeight - halfBorder];
switch (this._arrowSide) {
case St.Side.TOP:
}
_calculateArrowSide(arrowSide) {
- let sourceTopLeft = this._sourceExtents.get_top_left();
- let sourceBottomRight = this._sourceExtents.get_bottom_right();
- let [, , boxWidth, boxHeight] = this.get_preferred_size();
- let workarea = this._workArea;
+ const sourceTopLeft = this._sourceExtents.get_top_left();
+ const sourceBottomRight = this._sourceExtents.get_bottom_right();
+ const [, , boxWidth, boxHeight] = this.get_preferred_size();
+ const workarea = this._workArea;
switch (arrowSide) {
case St.Side.TOP:
}
_updateFlip(allocationBox) {
- let arrowSide = this._calculateArrowSide(this._userArrowSide);
+ const arrowSide = this._calculateArrowSide(this._userArrowSide);
if (this._arrowSide !== arrowSide) {
this._arrowSide = arrowSide;
this._reposition(allocationBox);
function _isWorkDay(date) {
/* Translators: Enter 0-6 (Sunday-Saturday) for non-work days. Examples: "0" (Sunday) "6" (Saturday) "06" (Sunday and Saturday). */
- let days = C_('calendar-no-work', '06');
+ const days = C_('calendar-no-work', '06');
return !days.includes(date.getDay().toString());
}
function _getBeginningOfDay(date) {
- let ret = new Date(date.getTime());
+ const ret = new Date(date.getTime());
ret.setHours(0);
ret.setMinutes(0);
ret.setSeconds(0);
}
function _getCalendarDayAbbreviation(dayNumber) {
- let abbreviations = [
+ const abbreviations = [
/* Translators: Calendar grid abbreviation for Sunday.
*
* NOTE: These grid abbreviations are always shown together
}
getEvents(_begin, _end) {
- let result = [];
+ const result = [];
return result;
}
const [id, summary, startTime, endTime] = appointments[n];
const date = new Date(startTime * 1000);
const end = new Date(endTime * 1000);
- let event = new CalendarEvent(id, date, end, summary);
+ const event = new CalendarEvent(id, date, end, summary);
/* It's a recurring event */
if (!id.endsWith('\n')) {
const parentId = id.substring(0, id.lastIndexOf('\n') + 1);
}
getEvents(begin, end) {
- let result = [...this._getFilteredEvents(begin, end)];
+ const result = [...this._getFilteredEvents(begin, end)];
result.sort((event1, event2) => {
// sort events by end time on ending day
- let d1 = event1.date < begin && event1.end <= end ? event1.end : event1.date;
- let d2 = event2.date < begin && event2.end <= end ? event2.end : event2.date;
+ const d1 = event1.date < begin && event1.end <= end ? event1.end : event1.date;
+ const d2 = event2.date < begin && event2.end <= end ? event2.end : event2.date;
return d1.getTime() - d2.getTime();
});
return result;
}
hasEvents(day) {
- let dayBegin = _getBeginningOfDay(day);
- let dayEnd = _getEndOfDay(day);
+ const dayBegin = _getBeginningOfDay(day);
+ const dayEnd = _getEndOfDay(day);
const {done} = this._getFilteredEvents(dayBegin, dayEnd).next();
return !done;
this._selectedDate = date;
- let datetime = GLib.DateTime.new_from_unix_local(
+ const datetime = GLib.DateTime.new_from_unix_local(
this._selectedDate.getTime() / 1000);
this.emit('selected-date-changed', datetime);
}
_buildHeader() {
- let layout = this.layout_manager;
- let offsetCols = this._useWeekdate ? 1 : 0;
+ const layout = this.layout_manager;
+ const offsetCols = this._useWeekdate ? 1 : 0;
this.destroy_all_children();
// Top line of the calendar '<| September 2009 |>'
// We need to figure out the abbreviated localized names for the days of the week;
// we do this by just getting the next 7 days starting from right now and then putting
// them in the right cell in the table. It doesn't matter if we add them in order
- let iter = new Date(this._selectedDate);
+ const iter = new Date(this._selectedDate);
iter.setSeconds(0); // Leap second protection. Hah!
iter.setHours(12);
for (let i = 0; i < 7; i++) {
// Could use formatDateWithCFormatString(iter, '%a') but that normally gives three characters
// and we want, ideally, a single character for e.g. S M T W T F S
- let customDayAbbrev = _getCalendarDayAbbreviation(iter.getDay());
- let label = new St.Label({
+ const customDayAbbrev = _getCalendarDayAbbreviation(iter.getDay());
+ const label = new St.Label({
style_class: 'calendar-day-heading',
text: customDayAbbrev,
can_focus: true,
_onPrevMonthButtonClicked() {
let newDate = new Date(this._selectedDate);
- let oldMonth = newDate.getMonth();
+ const oldMonth = newDate.getMonth();
if (oldMonth === 0) {
newDate.setMonth(11);
newDate.setFullYear(newDate.getFullYear() - 1);
if (newDate.getMonth() !== 11) {
- let day = 32 - new Date(newDate.getFullYear() - 1, 11, 32).getDate();
+ const day = 32 - new Date(newDate.getFullYear() - 1, 11, 32).getDate();
newDate = new Date(newDate.getFullYear() - 1, 11, day);
}
} else {
newDate.setMonth(oldMonth - 1);
if (newDate.getMonth() !== oldMonth - 1) {
- let day = 32 - new Date(newDate.getFullYear(), oldMonth - 1, 32).getDate();
+ const day = 32 - new Date(newDate.getFullYear(), oldMonth - 1, 32).getDate();
newDate = new Date(newDate.getFullYear(), oldMonth - 1, day);
}
}
_onNextMonthButtonClicked() {
let newDate = new Date(this._selectedDate);
- let oldMonth = newDate.getMonth();
+ const oldMonth = newDate.getMonth();
if (oldMonth === 11) {
newDate.setMonth(0);
newDate.setFullYear(newDate.getFullYear() + 1);
if (newDate.getMonth() !== 0) {
- let day = 32 - new Date(newDate.getFullYear() + 1, 0, 32).getDate();
+ const day = 32 - new Date(newDate.getFullYear() + 1, 0, 32).getDate();
newDate = new Date(newDate.getFullYear() + 1, 0, day);
}
} else {
newDate.setMonth(oldMonth + 1);
if (newDate.getMonth() !== oldMonth + 1) {
- let day = 32 - new Date(newDate.getFullYear(), oldMonth + 1, 32).getDate();
+ const day = 32 - new Date(newDate.getFullYear(), oldMonth + 1, 32).getDate();
newDate = new Date(newDate.getFullYear(), oldMonth + 1, day);
}
}
}
_rebuildCalendar() {
- let now = new Date();
+ const now = new Date();
// Remove everything but the topBox and the weekday labels
- let children = this.get_children();
+ const children = this.get_children();
for (let i = this._firstDayIndex; i < children.length; i++)
children[i].destroy();
// Actually computing the number of weeks is complex, but we know that the
// problematic categories (2 and 4) always start on week start, and that
// all months at the end have 6 weeks.
- let beginDate = new Date(
+ const beginDate = new Date(
this._selectedDate.getFullYear(), this._selectedDate.getMonth(), 1);
this._calendarBegin = new Date(beginDate);
this._markedAsToday = now;
- let daysToWeekStart = (7 + beginDate.getDay() - this._weekStart) % 7;
- let startsOnWeekStart = daysToWeekStart === 0;
- let weekPadding = startsOnWeekStart ? 7 : 0;
+ const daysToWeekStart = (7 + beginDate.getDay() - this._weekStart) % 7;
+ const startsOnWeekStart = daysToWeekStart === 0;
+ const weekPadding = startsOnWeekStart ? 7 : 0;
beginDate.setDate(beginDate.getDate() - (weekPadding + daysToWeekStart));
- let layout = this.layout_manager;
- let iter = new Date(beginDate);
+ const layout = this.layout_manager;
+ const iter = new Date(beginDate);
let row = 2;
// nRows here means 6 weeks + one header + one navbar
- let nRows = 8;
+ const nRows = 8;
while (row < nRows) {
- let button = new St.Button({
+ const button = new St.Button({
// xgettext:no-javascript-format
label: formatDateWithCFormatString(iter, C_('date day number format', '%d')),
can_focus: true,
});
- let rtl = button.get_text_direction() === Clutter.TextDirection.RTL;
+ const rtl = button.get_text_direction() === Clutter.TextDirection.RTL;
if (this._eventSource instanceof EmptyEventSource)
button.reactive = false;
this._shouldDateGrabFocus = false;
});
- let hasEvents = this._eventSource.hasEvents(iter);
+ const hasEvents = this._eventSource.hasEvents(iter);
let styleClass = 'calendar-day';
if (_isWorkDay(iter))
if (row === 2)
styleClass = `calendar-day-top ${styleClass}`;
- let leftMost = rtl
+ const leftMost = rtl
? iter.getDay() === (this._weekStart + 6) % 7
: iter.getDay() === this._weekStart;
if (leftMost)
button.style_class = styleClass;
- let offsetCols = this._useWeekdate ? 1 : 0;
+ const offsetCols = this._useWeekdate ? 1 : 0;
let col;
if (rtl)
col = 6 - (7 + iter.getDay() - this._weekStart) % 7;
style_class: 'calendar-week-number',
can_focus: true,
});
- let weekFormat = Shell.util_translate_time_string(N_('Week %V'));
+ const weekFormat = Shell.util_translate_time_string(N_('Week %V'));
label.clutter_text.y_align = Clutter.ActorAlign.CENTER;
label.accessible_name = formatDateWithCFormatString(iter, weekFormat);
layout.attach(label, rtl ? 7 : 0, row, 1, 1);
}
_update() {
- let now = new Date();
+ const now = new Date();
if (sameYear(this._selectedDate, now))
this._monthLabel.text = formatDateWithCFormatString(this._selectedDate, this._headerFormatWithoutYear);
this._placeholder = new Placeholder();
this.add_child(this._placeholder);
- let box = new St.BoxLayout({
+ const box = new St.BoxLayout({
orientation: Clutter.Orientation.VERTICAL,
x_expand: true,
y_expand: true,
});
box.add_child(this._scrollView);
- let hbox = new St.BoxLayout({style_class: 'message-list-controls'});
+ const hbox = new St.BoxLayout({style_class: 'message-list-controls'});
box.add_child(hbox);
this._clearButton = new St.Button({
export const CheckBox = GObject.registerClass(
class CheckBox extends St.Button {
_init(label) {
- let container = new St.BoxLayout({
+ const container = new St.BoxLayout({
x_expand: true,
y_expand: true,
});
}
_createDialogContent() {
- let tracker = Shell.WindowTracker.get_default();
- let windowApp = tracker.get_window_app(this._window);
+ const tracker = Shell.WindowTracker.get_default();
+ const windowApp = tracker.get_window_app(this._window);
/* Translators: %s is an application name */
- let title = _('“%s” Is Not Responding').format(windowApp.get_name());
- let description = _('You may choose to wait a short while for it to ' +
+ const title = _('“%s” Is Not Responding').format(windowApp.get_name());
+ const description = _('You may choose to wait a short while for it to ' +
'continue or force the app to quit entirely');
return new Dialog.MessageDialogContent({title, description});
}
if (this._window.get_client_type() !== Meta.WindowClientType.WAYLAND)
return;
- let {scaleFactor} = St.ThemeContext.get_for_stage(global.stage);
+ const {scaleFactor} = St.ThemeContext.get_for_stage(global.stage);
this._dialog.set_scale(1 / scaleFactor, 1 / scaleFactor);
}
if (this._dialog)
return;
- let windowActor = this._window.get_compositor_private();
+ const windowActor = this._window.get_compositor_private();
this._dialog = new Dialog.Dialog(windowActor, 'close-dialog');
this._dialog.width = windowActor.width;
this._dialog.height = windowActor.height;
global.focus_manager.add_group(this._dialog);
- let themeContext = St.ThemeContext.get_for_stage(global.stage);
+ const themeContext = St.ThemeContext.get_for_stage(global.stage);
themeContext.connect('notify::scale-factor', this._updateScale.bind(this));
this._updateScale();
// We set the effect on the surface actor, so the dialog itself
// (which is a child of the MetaWindowActor) does not get the
// effect applied itself.
- let windowActor = this._window.get_compositor_private();
- let surfaceActor = windowActor.get_first_child();
- let effect = new Clutter.BrightnessContrastEffect();
+ const windowActor = this._window.get_compositor_private();
+ const surfaceActor = windowActor.get_first_child();
+ const effect = new Clutter.BrightnessContrastEffect();
effect.set_brightness(FROZEN_WINDOW_BRIGHTNESS);
surfaceActor.add_effect_with_name('gnome-shell-frozen-window', effect);
}
_removeWindowEffect() {
- let windowActor = this._window.get_compositor_private();
- let surfaceActor = windowActor.get_first_child();
+ const windowActor = this._window.get_compositor_private();
+ const surfaceActor = windowActor.get_first_child();
surfaceActor.remove_effect_by_name('gnome-shell-frozen-window');
}
if (Meta.is_wayland_compositor())
return;
- let focusWindow = global.display.focus_window;
- let keyFocus = global.stage.key_focus;
+ const focusWindow = global.display.focus_window;
+ const keyFocus = global.stage.key_focus;
let shouldTrack;
if (focusWindow != null)
this._dialog._dialog.remove_all_transitions();
- let dialog = this._dialog;
+ const dialog = this._dialog;
this._dialog = null;
this._removeWindowEffect();
}
async _sessionModeUpdated() {
- let newEnabledComponents = Main.sessionMode.components;
+ const newEnabledComponents = Main.sessionMode.components;
await Promise.allSettled([...newEnabledComponents
.filter(name => !this._enabledComponents.includes(name))
}
async _importComponent(name) {
- let module = await import(`./components/${name}.js`);
+ const module = await import(`./components/${name}.js`);
return module.Component;
}
if (Main.sessionMode.isLocked)
return null;
- let constructor = await this._importComponent(name);
+ const constructor = await this._importComponent(name);
component = new constructor();
this._allComponents[name] = component;
return component;
}
async _enableComponent(name) {
- let component = await this._ensureComponent(name);
+ const component = await this._ensureComponent(name);
if (component)
component.enable();
}
_disableComponent(name) {
- let component = this._allComponents[name];
+ const component = this._allComponents[name];
if (component == null)
return;
component.disable();
}
_startupMountAll() {
- let volumes = this._volumeMonitor.get_volumes();
+ const volumes = this._volumeMonitor.get_volumes();
volumes.forEach(volume => {
this._checkAndMountVolume(volume, {
checkSession: false,
if (!this._session.SessionIsActive)
return;
- let player = global.display.get_sound_player();
+ const player = global.display.get_sound_player();
player.play_from_theme('device-added-media',
_('External drive connected'),
null);
if (!this._session.SessionIsActive)
return;
- let player = global.display.get_sound_player();
+ const player = global.display.get_sound_player();
player.play_from_theme('device-removed-media',
_('External drive disconnected'),
null);
}
if (params.useMountOp) {
- let operation = new ShellMountOperation.ShellMountOperation(volume);
+ const operation = new ShellMountOperation.ShellMountOperation(volume);
this._mountVolume(volume, operation, params.allowAutorun);
} else {
this._mountVolume(volume, null, params.allowAutorun);
}
_reaskPassword(volume) {
- let prevOperation = this._activeOperations.get(volume);
+ const prevOperation = this._activeOperations.get(volume);
const existingDialog = prevOperation?.borrowDialog();
- let operation =
+ const operation =
new ShellMountOperation.ShellMountOperation(volume, {existingDialog});
this._mountVolume(volume, operation);
}
_closeOperation(volume) {
- let operation = this._activeOperations.get(volume);
+ const operation = this._activeOperations.get(volume);
if (!operation)
return;
operation.close();
}
_allowAutorunExpire(volume) {
- let id = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, AUTORUN_EXPIRE_TIMEOUT_SECS, () => {
+ const id = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, AUTORUN_EXPIRE_TIMEOUT_SECS, () => {
volume.allowAutorun = false;
delete volume._allowAutorunExpireId;
return GLib.SOURCE_REMOVE;
// misc utils
function shouldAutorunMount(mount) {
- let root = mount.get_root();
- let volume = mount.get_volume();
+ const root = mount.get_root();
+ const volume = mount.get_volume();
if (!volume || !volume.allowAutorun)
return false;
}
function isMountRootHidden(root) {
- let path = root.get_path();
+ const path = root.get_path();
// skip any mounts in hidden directory hierarchies
return path.includes('/.');
// If the mount doesn't have an associated volume, that means it's
// an uninteresting filesystem. Most devices that we care about will
// have a mount, like media players and USB sticks.
- let volume = mount.get_volume();
+ const volume = mount.get_volume();
if (volume == null)
return true;
}
function startAppForMount(app, mount) {
- let files = [];
- let root = mount.get_root();
+ const files = [];
+ const root = mount.get_root();
let retval = false;
files.push(root);
}
async guessContentTypes(mount) {
- let autorunEnabled = !this._settings.get_boolean(SETTING_DISABLE_AUTORUN);
- let shouldScan = autorunEnabled && !isMountNonLocal(mount);
+ const autorunEnabled = !this._settings.get_boolean(SETTING_DISABLE_AUTORUN);
+ const shouldScan = autorunEnabled && !isMountNonLocal(mount);
let contentTypes = [];
if (shouldScan) {
}
_getAutorunSettingForType(contentType) {
- let runApp = this._settings.get_strv(SETTING_START_APP);
+ const runApp = this._settings.get_strv(SETTING_START_APP);
if (runApp.includes(contentType))
return AutorunSetting.RUN;
- let ignore = this._settings.get_strv(SETTING_IGNORE);
+ const ignore = this._settings.get_strv(SETTING_IGNORE);
if (ignore.includes(contentType))
return AutorunSetting.IGNORE;
- let openFiles = this._settings.get_strv(SETTING_OPEN_FOLDER);
+ const openFiles = this._settings.get_strv(SETTING_OPEN_FOLDER);
if (openFiles.includes(contentType))
return AutorunSetting.FILES;
this.prompt.connect('show-confirm', this._onShowConfirm.bind(this));
this.prompt.connect('prompt-close', this._onHidePrompt.bind(this));
- let content = new Dialog.MessageDialogContent();
+ const content = new Dialog.MessageDialogContent();
this.prompt.bind_property('message',
content, 'title', GObject.BindingFlags.SYNC_CREATE);
this.prompt.bind_property('description',
content, 'description', GObject.BindingFlags.SYNC_CREATE);
- let passwordBox = new St.BoxLayout({
+ const passwordBox = new St.BoxLayout({
style_class: 'prompt-dialog-password-layout',
orientation: Clutter.Orientation.VERTICAL,
});
this.prompt.set_password_actor(this._passwordEntry.clutter_text);
this.prompt.set_confirm_actor(this._confirmEntry.clutter_text);
- let warningBox = new St.BoxLayout({orientation: Clutter.Orientation.VERTICAL});
+ const warningBox = new St.BoxLayout({orientation: Clutter.Orientation.VERTICAL});
- let capsLockWarning = new ShellEntry.CapsLockWarning();
- let syncCapsLockWarningVisibility = () => {
+ const capsLockWarning = new ShellEntry.CapsLockWarning();
+ const syncCapsLockWarningVisibility = () => {
capsLockWarning.visible =
this.prompt.password_visible || this.prompt.confirm_visible;
};
this.prompt.connect('notify::confirm-visible', syncCapsLockWarningVisibility);
warningBox.add_child(capsLockWarning);
- let warning = new St.Label({style_class: 'prompt-dialog-error-label'});
+ const warning = new St.Label({style_class: 'prompt-dialog-error-label'});
warning.clutter_text.ellipsize = Pango.EllipsizeMode.NONE;
warning.clutter_text.line_wrap = true;
this.prompt.bind_property('warning',
_init() {
super._init();
this.connect('new-prompt', () => {
- let dialog = this._enabled
+ const dialog = this._enabled
? new KeyringDialog()
: new KeyringDummyDialog();
this._currentPrompt = dialog.prompt;
else
this._content = this._getContent();
- let contentBox = new Dialog.MessageDialogContent({
+ const contentBox = new Dialog.MessageDialogContent({
title: this._content.title,
description: this._content.message,
});
let initialFocusSet = false;
for (let i = 0; i < this._content.secrets.length; i++) {
- let secret = this._content.secrets[i];
- let reactive = secret.key != null;
+ const secret = this._content.secrets[i];
+ const reactive = secret.key != null;
- let entryParams = {
+ const entryParams = {
style_class: 'prompt-dialog-password-entry',
hint_text: secret.label,
text: secret.value,
}
if (this._content.secrets.some(s => s.password)) {
- let capsLockWarning = new ShellEntry.CapsLockWarning();
+ const capsLockWarning = new ShellEntry.CapsLockWarning();
contentBox.add_child(capsLockWarning);
}
if (flags & NM.SecretAgentGetSecretsFlags.WPS_PBC_ACTIVE) {
- let descriptionLabel = new St.Label({
+ const descriptionLabel = new St.Label({
text: _('Alternatively you can connect by pushing the “WPS” button on your router'),
style_class: 'message-dialog-description',
});
_updateOkButton() {
let valid = true;
for (let i = 0; i < this._content.secrets.length; i++) {
- let secret = this._content.secrets[i];
+ const secret = this._content.secrets[i];
valid &&= secret.valid;
}
_onOk() {
let valid = true;
for (let i = 0; i < this._content.secrets.length; i++) {
- let secret = this._content.secrets[i];
+ const secret = this._content.secrets[i];
valid &&= secret.valid;
if (secret.key !== null) {
if (this._settingName === 'vpn')
}
_validateWpaPsk(secret) {
- let value = secret.value;
+ const value = secret.value;
if (value.length === 64) {
// must be composed of hexadecimal digits only
for (let i = 0; i < 64; i++) {
}
_validateStaticWep(secret) {
- let value = secret.value;
+ const value = secret.value;
if (secret.wep_key_type === NM.WepKeyType.KEY) {
if (value.length === 10 || value.length === 26) {
for (let i = 0; i < value.length; i++) {
}
_getWirelessSecrets(secrets, _wirelessSetting) {
- let wirelessSecuritySetting = this._connection.get_setting_wireless_security();
+ const wirelessSecuritySetting = this._connection.get_setting_wireless_security();
if (this._settingName === '802-1x') {
this._get8021xSecrets(secrets);
}
_get8021xSecrets(secrets) {
- let ieee8021xSetting = this._connection.get_setting_802_1x();
+ const ieee8021xSetting = this._connection.get_setting_802_1x();
/* If hints were given we know exactly what we need to ask */
if (this._settingName === '802-1x' && this._hints.length) {
}
_getPPPoESecrets(secrets) {
- let pppoeSetting = this._connection.get_setting_pppoe();
+ const pppoeSetting = this._connection.get_setting_pppoe();
secrets.push({
label: _('Username'),
key: 'username',
}
_getContent() {
- let connectionSetting = this._connection.get_setting_connection();
- let connectionType = connectionSetting.get_connection_type();
+ const connectionSetting = this._connection.get_setting_connection();
+ const connectionType = connectionSetting.get_connection_type();
let wirelessSetting;
let ssid;
- let content = { };
+ const content = { };
content.secrets = [];
switch (connectionType) {
break;
case 'gsm':
if (this._hints.includes('pin')) {
- let gsmSetting = this._connection.get_setting_gsm();
+ const gsmSetting = this._connection.get_setting_gsm();
content.title = _('PIN code required');
content.message = _('PIN code is needed for the mobile broadband device');
content.secrets.push({
this._content = [];
this._shellDialog = null;
- let connectionSetting = connection.get_setting_connection();
+ const connectionSetting = connection.get_setting_connection();
const argv = [
authHelper.fileName,
try {
const launchContext = global.create_app_launch_context(0, -1);
- let [pid, stdin, stdout, stderr] =
+ const [pid, stdin, stdout, stderr] =
Shell.util_spawn_async_with_pipes(
null, /* pwd */
argv,
return;
}
- let [exited, exitStatus] = Shell.util_wifexited(status);
+ const [exited, exitStatus] = Shell.util_wifexited(status);
if (exited) {
if (exitStatus !== 0)
}
_showNewStyleDialog() {
- let keyfile = new GLib.KeyFile();
+ const keyfile = new GLib.KeyFile();
let data;
let contentOverride;
secrets: [],
};
- let [groups, len_] = keyfile.get_groups();
+ const [groups, len_] = keyfile.get_groups();
for (let i = 0; i < groups.length; i++) {
if (groups[i] === VPN_UI_GROUP)
continue;
- let value = keyfile.get_string(groups[i], 'Value');
- let shouldAsk = keyfile.get_boolean(groups[i], 'ShouldAsk');
+ const value = keyfile.get_string(groups[i], 'Value');
+ const shouldAsk = keyfile.get_boolean(groups[i], 'ShouldAsk');
if (shouldAsk) {
contentOverride.secrets.push({
}
_writeConnection() {
- let vpnSetting = this._connection.get_setting_vpn();
+ const vpnSetting = this._connection.get_setting_vpn();
try {
vpnSetting.foreach_data_item((key, value) => {
_showNotification(requestId, connection, settingName, hints, flags) {
let title, body;
- let connectionSetting = connection.get_setting_connection();
- let connectionType = connectionSetting.get_connection_type();
+ const connectionSetting = connection.get_setting_connection();
+ const connectionType = connectionSetting.get_connection_type();
switch (connectionType) {
case '802-11-wireless': {
- let wirelessSetting = connection.get_setting_wireless();
- let ssid = NM.utils_ssid_to_utf8(wirelessSetting.get_ssid().get_data());
+ const wirelessSetting = connection.get_setting_wireless();
+ const ssid = NM.utils_ssid_to_utf8(wirelessSetting.get_ssid().get_data());
title = _('Authentication required');
body = _('Passwords or encryption keys are required to access the wireless network “%s”').format(ssid);
break;
return;
}
- let dialog = new NetworkSecretDialog(this._native, requestId, connection, settingName, hints, flags);
+ const dialog = new NetworkSecretDialog(this._native, requestId, connection, settingName, hints, flags);
dialog.connect('destroy', () => {
delete this._dialogs[requestId];
});
}
async _vpnRequest(requestId, connection, hints, flags) {
- let vpnSetting = connection.get_setting_vpn();
- let serviceType = vpnSetting.service_type;
+ const vpnSetting = connection.get_setting_vpn();
+ const serviceType = vpnSetting.service_type;
- let binary = await this._findAuthBinary(serviceType);
+ const binary = await this._findAuthBinary(serviceType);
if (!binary) {
log('Invalid VPN service type (cannot find authentication binary)');
return;
}
- let vpnRequest = new VPNRequestHandler(this._native, requestId, binary, serviceType, connection, hints, flags);
+ const vpnRequest = new VPNRequestHandler(this._native, requestId, binary, serviceType, connection, hints, flags);
vpnRequest.connect('destroy', () => {
delete this._vpnRequests[requestId];
});
this.connect('closed', this._onDialogClosed.bind(this));
- let title = _('Authentication Required');
+ const title = _('Authentication Required');
- let headerContent = new Dialog.MessageDialogContent({title, description});
+ const headerContent = new Dialog.MessageDialogContent({title, description});
this.contentLayout.add_child(headerContent);
- let bodyContent = new Dialog.MessageDialogContent();
+ const bodyContent = new Dialog.MessageDialogContent();
if (userNames.length > 1) {
log(`polkitAuthenticationAgent: Received ${userNames.length} ` +
this._user = AccountsService.UserManager.get_default().get_user(userName);
- let userBox = new St.BoxLayout({
+ const userBox = new St.BoxLayout({
style_class: 'polkit-dialog-user-layout',
orientation: Clutter.Orientation.VERTICAL,
});
userBox.add_child(this._userLabel);
- let passwordBox = new St.BoxLayout({
+ const passwordBox = new St.BoxLayout({
style_class: 'prompt-dialog-password-layout',
orientation: Clutter.Orientation.VERTICAL,
});
GObject.BindingFlags.SYNC_CREATE);
passwordBox.add_child(this._passwordEntry);
- let warningBox = new St.BoxLayout({orientation: Clutter.Orientation.VERTICAL});
+ const warningBox = new St.BoxLayout({orientation: Clutter.Orientation.VERTICAL});
- let capsLockWarning = new ShellEntry.CapsLockWarning();
+ const capsLockWarning = new ShellEntry.CapsLockWarning();
this._passwordEntry.bind_property('visible',
capsLockWarning, 'visible',
GObject.BindingFlags.SYNC_CREATE);
}
_onEntryActivate() {
- let response = this._passwordEntry.get_text();
+ const response = this._passwordEntry.get_text();
if (response.length === 0)
return;
this._sessionRequestTimeoutId = 0;
}
- let resetDialog = () => {
+ const resetDialog = () => {
this._sessionRequestTimeoutId = 0;
if (this.state !== ModalDialog.State.OPENED)
if (!this._user.is_loaded)
return;
- let userName = this._user.get_user_name();
- let realName = this._user.get_real_name();
+ const userName = this._user.get_user_name();
+ const realName = this._user.get_real_name();
if (userName !== 'root')
this._userLabel.set_text(realName);
if (a.sortGroup !== b.sortGroup)
return a.sortGroup - b.sortGroup;
- let [ax] = a.proxy.get_transformed_position();
- let [bx] = b.proxy.get_transformed_position();
+ const [ax] = a.proxy.get_transformed_position();
+ const [bx] = b.proxy.get_transformed_position();
return ax - bx;
}
popup(backward, binding, mask) {
// Start with the set of focus groups that are currently mapped
- let items = this._items.filter(item => item.proxy.mapped);
+ const items = this._items.filter(item => item.proxy.mapped);
// And add the windows metacity would show in its Ctrl-Alt-Tab list
if (Main.sessionMode.hasWindows && !Main.overview.visible) {
- let display = global.display;
- let workspaceManager = global.workspace_manager;
- let activeWorkspace = workspaceManager.get_active_workspace();
- let windows = display.get_tab_list(Meta.TabList.DOCKS,
+ const display = global.display;
+ const workspaceManager = global.workspace_manager;
+ const activeWorkspace = workspaceManager.get_active_workspace();
+ const windows = display.get_tab_list(Meta.TabList.DOCKS,
activeWorkspace);
- let windowTracker = Shell.WindowTracker.get_default();
+ const windowTracker = Shell.WindowTracker.get_default();
for (let i = 0; i < windows.length; i++) {
let icon = null;
let iconName = null;
}
box.add_child(icon);
- let text = new St.Label({
+ const text = new St.Label({
text: item.name,
x_align: Clutter.ActorAlign.CENTER,
});
}
vfunc_get_preferred_height(forWidth) {
- let themeNode = this.get_theme_node();
+ const themeNode = this.get_theme_node();
forWidth = themeNode.adjust_for_width(forWidth);
- let [minHeight, natHeight] = super.vfunc_get_preferred_height(forWidth);
+ const [minHeight, natHeight] = super.vfunc_get_preferred_height(forWidth);
return themeNode.adjust_preferred_height(
minHeight * this.scale_y,
natHeight * this.scale_y);
}
vfunc_get_preferred_width(forHeight) {
- let themeNode = this.get_theme_node();
+ const themeNode = this.get_theme_node();
forHeight = themeNode.adjust_for_height(forHeight);
- let [minWidth, natWidth] = super.vfunc_get_preferred_width(forHeight);
+ const [minWidth, natWidth] = super.vfunc_get_preferred_width(forHeight);
return themeNode.adjust_preferred_width(
minWidth * this.scale_x,
natWidth * this.scale_x);
this.label.opacity = 0;
this.label.show();
- let [stageX, stageY] = this.get_transformed_position();
+ const [stageX, stageY] = this.get_transformed_position();
const itemWidth = this.allocation.get_width();
const xOffset = Math.floor((itemWidth - labelWidth) / 2);
const x = Math.clamp(stageX + xOffset, 0, global.stage.width - labelWidth);
- let node = this.label.get_theme_node();
+ const node = this.label.get_theme_node();
const yOffset = node.get_length('-y-offset');
const y = stageY - this.label.height - yOffset;
if (this.child == null)
return;
- let time = animate ? DASH_ANIMATION_TIME : 0;
+ const time = animate ? DASH_ANIMATION_TIME : 0;
this.ease({
scale_x: 1,
scale_y: 1,
if (!global.settings.is_writable('favorite-apps'))
return false;
- let id = app.get_id();
- let isFavorite = AppFavorites.getAppFavorites().isFavorite(id);
+ const id = app.get_id();
+ const isFavorite = AppFavorites.getAppFavorites().isFavorite(id);
return isFavorite;
}
setDragApp(app) {
- let canRemove = this._canRemoveApp(app);
+ const canRemove = this._canRemoveApp(app);
this.toggleButton.set_hover(canRemove);
if (this._iconActor)
if (!this._canRemoveApp(app))
return false;
- let id = app.get_id();
+ const id = app.get_id();
const laters = global.compositor.get_laters();
laters.add(Meta.LaterType.BEFORE_REDRAW, () => {
if (app == null)
return DND.DragMotionResult.CONTINUE;
- let showAppsHovered =
+ const showAppsHovered =
this._showAppsIcon.contains(dragEvent.targetActor);
if (!this._box.contains(dragEvent.targetActor) || showAppsHovered)
}
_appIdListToHash(apps) {
- let ids = {};
+ const ids = {};
for (let i = 0; i < apps.length; i++)
ids[apps[i].get_id()] = apps[i];
return ids;
}
_createAppItem(app) {
- let item = new DashItemContainer();
- let appIcon = new DashIcon(app);
+ const item = new DashItemContainer();
+ const appIcon = new DashIcon(app);
appIcon.connect('menu-state-changed', (o, opened) => {
this._itemMenuStateChanged(item, opened);
}
_syncLabel(item, appIcon) {
- let shouldShow = appIcon ? appIcon.shouldShowTooltip() : item.child.get_hover();
+ const shouldShow = appIcon ? appIcon.shouldShowTooltip() : item.child.get_hover();
if (shouldShow) {
if (this._showLabelTimeoutId === 0) {
- let timeout = this._labelShowing ? 0 : DASH_ITEM_HOVER_TIMEOUT;
+ const timeout = this._labelShowing ? 0 : DASH_ITEM_HOVER_TIMEOUT;
this._showLabelTimeoutId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, timeout,
() => {
this._labelShowing = true;
// icons (i.e. ignoring drag placeholders) and which are not
// animating out (which means they will be destroyed at the end of
// the animation)
- let iconChildren = this._box.get_children().filter(actor => {
+ const iconChildren = this._box.get_children().filter(actor => {
return actor.child &&
actor.child._delegate &&
actor.child._delegate.icon &&
x2: this._maxWidth,
y2: 42, /* whatever */
});
- let maxContent = themeNode.get_content_box(maxAllocation);
+ const maxContent = themeNode.get_content_box(maxAllocation);
let availWidth = maxContent.x2 - maxContent.x1;
- let spacing = themeNode.get_length('spacing');
+ const spacing = themeNode.get_length('spacing');
- let firstButton = iconChildren[0].child;
- let firstIcon = firstButton._delegate.icon;
+ const firstButton = iconChildren[0].child;
+ const firstIcon = firstButton._delegate.icon;
// Enforce valid spacings during the size request
firstIcon.icon.ensure_style();
const maxIconSize = Math.min(availWidth / iconChildren.length, availHeight);
- let scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
- let iconSizes = baseIconSizes.map(s => s * scaleFactor);
+ const scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
+ const iconSizes = baseIconSizes.map(s => s * scaleFactor);
let newIconSize = baseIconSizes[0];
for (let i = 0; i < iconSizes.length; i++) {
if (newIconSize === this.iconSize)
return;
- let oldIconSize = this.iconSize;
+ const oldIconSize = this.iconSize;
this.iconSize = newIconSize;
this.emit('icon-size-changed');
- let scale = oldIconSize / newIconSize;
+ const scale = oldIconSize / newIconSize;
for (let i = 0; i < iconChildren.length; i++) {
- let icon = iconChildren[i].child._delegate.icon;
+ const icon = iconChildren[i].child._delegate.icon;
// Set the new size immediately, to keep the icons' sizes
// in sync with this.iconSize
!this._shownInitially)
continue;
- let [targetWidth, targetHeight] = icon.icon.get_size();
+ const [targetWidth, targetHeight] = icon.icon.get_size();
// Scale the icon's texture to the previous size and
// tween to the new size
}
_redisplay() {
- let favorites = AppFavorites.getAppFavorites().getFavoriteMap();
+ const favorites = AppFavorites.getAppFavorites().getFavoriteMap();
- let running = this._appSystem.get_running();
+ const running = this._appSystem.get_running();
- let children = this._box.get_children().filter(actor => {
+ const children = this._box.get_children().filter(actor => {
return actor.child &&
actor.child._delegate &&
actor.child._delegate.app;
});
// Apps currently in the dash
- let oldApps = children.map(actor => actor.child._delegate.app);
+ const oldApps = children.map(actor => actor.child._delegate.app);
// Apps supposed to be in the dash
- let newApps = [];
+ const newApps = [];
- for (let id in favorites)
+ for (const id in favorites)
newApps.push(favorites[id]);
for (let i = 0; i < running.length; i++) {
- let app = running[i];
+ const app = running[i];
if (app.get_id() in favorites)
continue;
newApps.push(app);
// If above assumptions turns out to be a problem, we might need
// to use a more sophisticated algorithm, e.g. Longest Common
// Subsequence as used by diff.
- let addedItems = [];
- let removedActors = [];
+ const addedItems = [];
+ const removedActors = [];
let newIndex = 0;
let oldIndex = 0;
while (newIndex < newApps.length || oldIndex < oldApps.length) {
- let oldApp = oldApps.length > oldIndex ? oldApps[oldIndex] : null;
- let newApp = newApps.length > newIndex ? newApps[newIndex] : null;
+ const oldApp = oldApps.length > oldIndex ? oldApps[oldIndex] : null;
+ const newApp = newApps.length > newIndex ? newApps[newIndex] : null;
// No change at oldIndex/newIndex
if (oldApp === newApp) {
}
// App moved
- let nextApp = newApps.length > newIndex + 1
+ const nextApp = newApps.length > newIndex + 1
? newApps[newIndex + 1] : null;
- let insertHere = nextApp && nextApp === oldApp;
- let alreadyRemoved = removedActors.reduce((result, actor) => {
- let removedApp = actor.child._delegate.app;
+ const insertHere = nextApp && nextApp === oldApp;
+ const alreadyRemoved = removedActors.reduce((result, actor) => {
+ const removedApp = actor.child._delegate.app;
return result || removedApp === newApp;
}, false);
if (insertHere || alreadyRemoved) {
- let newItem = this._createAppItem(newApp);
+ const newItem = this._createAppItem(newApp);
addedItems.push({
app: newApp,
item: newItem,
}
for (let i = 0; i < removedActors.length; i++) {
- let item = removedActors[i];
+ const item = removedActors[i];
// Don't animate item removal when the overview is transitioning
// or hidden
// Skip animations on first run when adding the initial set
// of items, to avoid all items zooming in at once
- let animate = this._shownInitially && Main.overview.visible &&
+ const animate = this._shownInitially && Main.overview.visible &&
!Main.overview.animationInProgress;
if (!this._shownInitially)
if (!global.settings.is_writable('favorite-apps'))
return DND.DragMotionResult.NO_DROP;
- let favorites = AppFavorites.getAppFavorites().getFavorites();
- let numFavorites = favorites.length;
+ const favorites = AppFavorites.getAppFavorites().getFavorites();
+ const numFavorites = favorites.length;
- let favPos = favorites.indexOf(app);
+ const favPos = favorites.indexOf(app);
- let children = this._box.get_children();
+ const children = this._box.get_children();
let numChildren = children.length;
let boxWidth = this._box.width;
if (!global.settings.is_writable('favorite-apps'))
return false;
- let id = app.get_id();
+ const id = app.get_id();
- let favorites = AppFavorites.getAppFavorites().getFavoriteMap();
+ const favorites = AppFavorites.getAppFavorites().getFavoriteMap();
- let srcIsFavorite = id in favorites;
+ const srcIsFavorite = id in favorites;
let favPos = 0;
- let children = this._box.get_children();
+ const children = this._box.get_children();
for (let i = 0; i < this._dragPlaceholderPos; i++) {
if (this._dragPlaceholder &&
children[i] === this._dragPlaceholder)
continue;
- let childId = children[i].child._delegate.app.get_id();
+ const childId = children[i].child._delegate.app.get_id();
if (childId === id)
continue;
if (childId in favorites)
const laters = global.compositor.get_laters();
laters.add(Meta.LaterType.BEFORE_REDRAW, () => {
- let appFavorites = AppFavorites.getAppFavorites();
+ const appFavorites = AppFavorites.getAppFavorites();
if (srcIsFavorite)
appFavorites.moveFavoriteToPos(id, favPos);
else
* @returns {boolean}
*/
function _isToday(date) {
- let now = new Date();
+ const now = new Date();
return now.getFullYear() === date.getFullYear() &&
now.getMonth() === date.getMonth() &&
now.getDate() === date.getDate();
const events =
this._eventSource.getEvents(this._startDate, this._endDate);
- for (let event of events) {
+ for (const event of events) {
const box = new St.BoxLayout({
style_class: 'event-box',
orientation: Clutter.Orientation.VERTICAL,
this._grid.destroy_all_children();
this._locations = [];
- let world = GWeather.Location.get_world();
- let clocks = this._settings.get_value('locations').deepUnpack();
+ const world = GWeather.Location.get_world();
+ const clocks = this._settings.get_value('locations').deepUnpack();
for (let i = 0; i < clocks.length; i++) {
- let l = world.deserialize(clocks[i]);
+ const l = world.deserialize(clocks[i]);
if (l && l.get_timezone() != null)
this._locations.push({location: l});
}
return tzA.get_offset(intA) - tzB.get_offset(intB);
});
- let layout = this._grid.layout_manager;
+ const layout = this._grid.layout_manager;
const title = this._locations.length === 0
? _('Add World Clocks…')
: _('World Clocks');
this.label_actor = header;
for (let i = 0; i < this._locations.length; i++) {
- let l = this._locations[i].location;
+ const l = this._locations[i].location;
- let name = l.get_city_name() || l.get_name();
+ const name = l.get_city_name() || l.get_name();
const label = new St.Label({
style_class: 'world-clocks-city',
text: name,
_updateTimeLabels() {
for (let i = 0; i < this._locations.length; i++) {
- let l = this._locations[i];
+ const l = this._locations[i];
const now = GLib.DateTime.new_now(l.location.get_timezone());
l.timeLabel.text = formatTime(now, {timeOnly: true});
}
_updateTimezoneLabels() {
for (let i = 0; i < this._locations.length; i++) {
- let l = this._locations[i];
+ const l = this._locations[i];
l.tzLabel.text = this._getTimezoneOffsetAtLocation(l.location);
}
}
this._weatherClient = new Weather.WeatherClient();
- let box = new St.BoxLayout({
+ const box = new St.BoxLayout({
style_class: 'weather-box',
orientation: Clutter.Orientation.VERTICAL,
x_expand: true,
this.child = box;
- let titleBox = new St.BoxLayout({style_class: 'weather-header-box'});
+ const titleBox = new St.BoxLayout({style_class: 'weather-header-box'});
this._titleLabel = new St.Label({
style_class: 'weather-header',
x_align: Clutter.ActorAlign.START,
});
titleBox.add_child(this._titleLocation);
- let layout = new Clutter.GridLayout({orientation: Clutter.Orientation.VERTICAL});
+ const layout = new Clutter.GridLayout({orientation: Clutter.Orientation.VERTICAL});
this._forecastGrid = new St.Widget({
style_class: 'weather-grid',
layout_manager: layout,
}
_getInfos() {
- let forecasts = this._weatherClient.info.get_forecast_list();
+ const forecasts = this._weatherClient.info.get_forecast_list();
- let now = GLib.DateTime.new_now_local();
+ const now = GLib.DateTime.new_now_local();
let current = GLib.DateTime.new_from_unix_local(0);
- let infos = [];
+ const infos = [];
for (let i = 0; i < forecasts.length; i++) {
const [valid, timestamp] = forecasts[i].get_value_update();
if (!valid || timestamp === 0)
}
_addForecasts() {
- let layout = this._forecastGrid.layout_manager;
+ const layout = this._forecastGrid.layout_manager;
- let infos = this._getInfos();
+ const infos = this._getInfos();
if (this._forecastGrid.text_direction === Clutter.TextDirection.RTL)
infos.reverse();
let col = 0;
infos.forEach(fc => {
const [valid_, timestamp] = fc.get_value_update();
- let timeStr = formatTime(new Date(timestamp * 1000), {
+ const timeStr = formatTime(new Date(timestamp * 1000), {
timeOnly: true,
ampm: false,
});
const [, tempValue] = fc.get_value_temp(GWeather.TemperatureUnit.DEFAULT);
const tempPrefix = Math.round(tempValue) >= 0 ? ' ' : '';
- let time = new St.Label({
+ const time = new St.Label({
style_class: 'weather-forecast-time',
text: timeStr,
x_align: Clutter.ActorAlign.CENTER,
});
- let icon = new St.Icon({
+ const icon = new St.Icon({
style_class: 'weather-forecast-icon',
icon_name: fc.get_symbolic_icon_name(),
x_align: Clutter.ActorAlign.CENTER,
x_expand: true,
});
- let temp = new St.Label({
+ const temp = new St.Label({
style_class: 'weather-forecast-temp',
text: `${tempPrefix}${Math.round(tempValue)}°`,
x_align: Clutter.ActorAlign.CENTER,
}
_setStatusLabel(text) {
- let layout = this._forecastGrid.layout_manager;
- let label = new St.Label({text});
+ const layout = this._forecastGrid.layout_manager;
+ const label = new St.Label({text});
layout.attach(label, 0, 0, 1, 1);
}
Main.messageTray.connect('source-removed', this._onSourceRemoved.bind(this));
Main.messageTray.connect('queue-changed', this._updateCount.bind(this));
- let sources = Main.messageTray.getSources();
+ const sources = Main.messageTray.getSources();
sources.forEach(source => this._onSourceAdded(null, source));
this._sync();
vfunc_allocate(container, allocation) {
super.vfunc_allocate(container, allocation);
- let [width, height] = allocation.get_size();
+ const [width, height] = allocation.get_size();
this._savedWidth = [width, width];
this._savedHeight = [height, height];
}
export const DateMenuButton = GObject.registerClass(
class DateMenuButton extends PanelMenu.Button {
_init() {
- let hbox;
-
super._init(0.5);
this._clockDisplay = new St.Label({style_class: 'clock'});
coordinate: Clutter.BindCoordinate.SIZE,
}));
- let box = new St.BoxLayout({style_class: 'clock-display-box'});
+ const box = new St.BoxLayout({style_class: 'clock-display-box'});
box.add_child(indicatorPad);
box.add_child(this._clockDisplay);
box.add_child(this._indicator);
this.add_child(box);
this.add_style_class_name('clock-display');
- let layout = new FreezableBinLayout();
- let bin = new St.Widget({layout_manager: layout});
+ const layout = new FreezableBinLayout();
+ const bin = new St.Widget({layout_manager: layout});
// For some minimal compatibility with PopupMenuItem
bin._delegate = this;
this.menu.box.add_child(bin);
this.menu.box.add_style_class_name('datemenu-popover');
- hbox = new St.BoxLayout({name: 'calendarArea'});
+ const hbox = new St.BoxLayout({name: 'calendarArea'});
bin.add_child(hbox);
this._calendar = new Calendar.Calendar();
this._calendar.connect('selected-date-changed', (_calendar, datetime) => {
- let date = _gDateTimeToDate(datetime);
+ const date = _gDateTimeToDate(datetime);
layout.frozen = !_isToday(date);
this._eventsItem.setDate(date);
});
this.menu.connect('open-state-changed', (menu, isOpen) => {
// Whenever the menu is opened, select today
if (isOpen) {
- let now = new Date();
+ const now = new Date();
this._calendar.setDate(now);
this._date.setDate(now);
this._eventsItem.setDate(now);
_sessionUpdated() {
let eventSource;
- let showEvents = Main.sessionMode.showCalendarEvents;
+ const showEvents = Main.sessionMode.showCalendarEvents;
if (showEvents)
eventSource = this._getEventSource();
else
if (event.type() === Clutter.EventType.KEY_PRESS) {
this._pressedKey = event.get_key_symbol();
} else if (event.type() === Clutter.EventType.KEY_RELEASE) {
- let pressedKey = this._pressedKey;
+ const pressedKey = this._pressedKey;
this._pressedKey = null;
- let symbol = event.get_key_symbol();
+ const symbol = event.get_key_symbol();
if (symbol !== pressedKey)
return Clutter.EVENT_PROPAGATE;
- let buttonInfo = this._buttonKeys[symbol];
+ const buttonInfo = this._buttonKeys[symbol];
if (!buttonInfo)
return Clutter.EVENT_PROPAGATE;
- let {button, action} = buttonInfo;
+ const {button, action} = buttonInfo;
if (action && button.reactive) {
action();
}
addButton(buttonInfo) {
- let {label, action, key} = buttonInfo;
- let isDefault = buttonInfo['default'];
+ const {label, action, key} = buttonInfo;
+ const isDefault = buttonInfo['default'];
let keys;
if (key)
else
keys = [];
- let button = new St.Button({
+ const button = new St.Button({
style_class: 'modal-dialog-button',
button_mask: St.ButtonMask.ONE | St.ButtonMask.THREE,
reactive: true,
if (this._initialKeyFocus == null || isDefault)
this._setInitialKeyFocus(button);
- for (let i in keys)
+ for (const i in keys)
this._buttonKeys[keys[i]] = buttonInfo;
this.buttonLayout.add_child(button);
_init(params) {
this._iconActorBin = new St.Bin();
- let textLayout = new St.BoxLayout({
+ const textLayout = new St.BoxLayout({
orientation: Clutter.Orientation.VERTICAL,
y_expand: true,
y_align: Clutter.ActorAlign.CENTER,
// If the user dragged from the source, then position
// the dragActor over it. Otherwise, center it
// around the pointer
- let [sourceX, sourceY] = this._dragActorSource.get_transformed_position();
+ const [sourceX, sourceY] = this._dragActorSource.get_transformed_position();
let x, y;
if (this._dragStartX > sourceX && this._dragStartX <= sourceX + this._dragActor.width &&
this._dragStartY > sourceY && this._dragStartY <= sourceY + this._dragActor.height) {
this._snapBackY = this._dragStartY + this._dragOffsetY;
this._snapBackScale = this._dragActor.scale_x;
- let origDragOffsetX = this._dragOffsetX;
- let origDragOffsetY = this._dragOffsetY;
- let [transX, transY] = this._dragActor.get_translation();
+ const origDragOffsetX = this._dragOffsetX;
+ const origDragOffsetY = this._dragOffsetY;
+ const [transX, transY] = this._dragActor.get_translation();
this._dragOffsetX -= transX;
this._dragOffsetY -= transY;
this._dragY + this._dragOffsetY);
if (this._dragActorMaxSize !== undefined) {
- let currentSize = Math.max(scaledWidth, scaledHeight);
+ const currentSize = Math.max(scaledWidth, scaledHeight);
if (currentSize > this._dragActorMaxSize) {
- let scale = this._dragActorMaxSize / currentSize;
- let origScale = this._dragActor.scale_x;
+ const scale = this._dragActorMaxSize / currentSize;
+ const origScale = this._dragActor.scale_x;
// The position of the actor changes as we scale
// around the drag position, but we can't just tween
this._updateHoverId = 0;
let target = this._pickTargetActor();
- let dragEvent = {
+ const dragEvent = {
x: this._dragX,
y: this._dragY,
dragActor: this._dragActor,
};
let targetActorDestroyHandlerId;
- let handleTargetActorDestroyClosure;
- handleTargetActorDestroyClosure = () => {
+ const handleTargetActorDestroyClosure = () => {
target = this._pickTargetActor();
dragEvent.targetActor = target;
targetActorDestroyHandlerId =
target.connect('destroy', handleTargetActorDestroyClosure);
for (let i = 0; i < dragMonitors.length; i++) {
- let motionFunc = dragMonitors[i].dragMotion;
+ const motionFunc = dragMonitors[i].dragMotion;
if (motionFunc) {
- let result = motionFunc(dragEvent);
+ const result = motionFunc(dragEvent);
if (result !== DragMotionResult.CONTINUE) {
global.display.set_cursor(DRAG_CURSOR_MAP[result]);
dragEvent.targetActor.disconnect(targetActorDestroyHandlerId);
while (target) {
if (target._delegate && target._delegate.handleDragOver) {
- let [r_, targX, targY] = target.transform_stage_point(this._dragX, this._dragY);
+ const [r_, targX, targY] = target.transform_stage_point(this._dragX, this._dragY);
// We currently loop through all parents on drag-over even if one of the children has handled it.
// We can check the return value of the function and break the loop if it's true if we don't want
// to continue checking the parents.
- let result = target._delegate.handleDragOver(
+ const result = target._delegate.handleDragOver(
this.actor._delegate,
this._dragActor,
targX,
}
_updateDragPosition(event) {
- let [stageX, stageY] = event.get_coords();
+ const [stageX, stageY] = event.get_coords();
this._dragX = stageX;
this._dragY = stageY;
this._dragActor.set_position(
}
_dragActorDropped(event) {
- let [dropX, dropY] = event.get_coords();
+ const [dropX, dropY] = event.get_coords();
let target = this._dragActor.get_stage().get_actor_at_pos(
Clutter.PickMode.ALL, dropX, dropY);
// We call observers only once per motion with the innermost
// target actor. If necessary, the observer can walk the
// parent itself.
- let dropEvent = {
+ const dropEvent = {
dropActor: this._dragActor,
targetActor: target,
clutterEvent: event,
};
for (let i = 0; i < dragMonitors.length; i++) {
- let dropFunc = dragMonitors[i].dragDrop;
+ const dropFunc = dragMonitors[i].dragDrop;
if (dropFunc) {
switch (dropFunc(dropEvent)) {
case DragDropResult.FAILURE:
while (target) {
if (target._delegate && target._delegate.acceptDrop) {
- let [r_, targX, targY] = target.transform_stage_point(dropX, dropY);
+ const [r_, targX, targY] = target.transform_stage_point(dropX, dropY);
let accepted = false;
try {
accepted = target._delegate.acceptDrop(this.actor._delegate,
if (this._dragActorSource && this._dragActorSource.visible) {
// Snap the clone back to its source
[x, y] = this._dragActorSource.get_transformed_position();
- let [sourceScaledWidth] = this._dragActorSource.get_transformed_size();
+ const [sourceScaledWidth] = this._dragActorSource.get_transformed_size();
scale = sourceScaledWidth ? sourceScaledWidth / this._dragActor.width : 0;
} else if (this._dragOrigParent) {
// Snap the actor back to its original position within
// its parent, adjusting for the fact that the parent
// may have been moved or scaled
- let [parentX, parentY] = this._dragOrigParent.get_transformed_position();
- let parentScale = _getRealActorScale(this._dragOrigParent);
+ const [parentX, parentY] = this._dragOrigParent.get_transformed_position();
+ const parentScale = _getRealActorScale(this._dragOrigParent);
x = parentX + parentScale * this._dragOrigX;
y = parentY + parentScale * this._dragOrigY;
}
_restoreDragActor(eventTime) {
- let [restoreX, restoreY, restoreScale] = this._getRestoreLocation();
+ const [restoreX, restoreY, restoreScale] = this._getRestoreLocation();
// fade the actor back in at its original location
this._dragActor.set_position(restoreX, restoreY);
return;
}
- let [snapBackX, snapBackY, snapBackScale] = this._getRestoreLocation();
+ const [snapBackX, snapBackY, snapBackScale] = this._getRestoreLocation();
this._animateDragEnd(eventTime, {
x: snapBackX,
}
function _setCheckBoxLabel(checkBox, text) {
- let label = checkBox.getLabelActor();
+ const label = checkBox.getLabelActor();
if (text) {
label.set_text(text);
// Show the warning if updates have already been triggered, but
// the user doesn't have enough permissions to cancel them.
- let updatesAllowed = this._updatesPermission && this._updatesPermission.allowed;
+ const updatesAllowed = this._updatesPermission && this._updatesPermission.allowed;
return this._updateInfo.UpdatePrepared && this._updateInfo.UpdateTriggered && !updatesAllowed;
}
_sync() {
- let open = this.state === ModalDialog.State.OPENING || this.state === ModalDialog.State.OPENED;
+ const open = this.state === ModalDialog.State.OPENING || this.state === ModalDialog.State.OPENED;
if (!open)
return;
- let dialogContent = DialogContent[this._type];
+ const dialogContent = DialogContent[this._type];
let subject = dialogContent.subject;
this._batteryWarning.visible = this._shouldShowLowBatteryWarning(dialogContent);
let description;
- let displayTime = _roundSecondsToInterval(
+ const displayTime = _roundSecondsToInterval(
this._totalSecondsToStayOpen, this._secondsLeft, 10);
if (this._user.is_loaded) {
- let realName = this._user.get_real_name();
+ const realName = this._user.get_real_name();
if (realName != null) {
if (dialogContent.subjectWithUser)
this._messageDialogContent.title = subject;
this._messageDialogContent.description = description;
- let hasApplications = this._applications.length > 0;
- let hasSessions = this._sessions.length > 0;
+ const hasApplications = this._applications.length > 0;
+ const hasSessions = this._sessions.length > 0;
this._applicationSection.visible = hasApplications;
this._sessionSection.visible = hasSessions;
_onCapturedEvent(actor, event) {
let altEnabled = false;
- let type = event.type();
+ const type = event.type();
if (type !== Clutter.EventType.KEY_PRESS && type !== Clutter.EventType.KEY_RELEASE)
return Clutter.EVENT_PROPAGATE;
- let key = event.get_key_symbol();
+ const key = event.get_key_symbol();
if (key !== Clutter.KEY_Alt_L && key !== Clutter.KEY_Alt_R)
return Clutter.EVENT_PROPAGATE;
key: Clutter.KEY_Escape,
});
- let dialogContent = DialogContent[this._type];
+ const dialogContent = DialogContent[this._type];
for (let i = 0; i < dialogContent.confirmButtons.length; i++) {
- let signal = dialogContent.confirmButtons[i].signal;
- let label = dialogContent.confirmButtons[i].label;
- let button = this.addButton({
+ const signal = dialogContent.confirmButtons[i].signal;
+ const label = dialogContent.confirmButtons[i].label;
+ const button = this.addButton({
action: () => {
- let signalId = this.connect('closed', () => {
+ const signalId = this.connect('closed', () => {
this.disconnect(signalId);
this._confirm(signal).catch(logError);
});
this._rebootButtonAlt = this.addButton({
action: () => {
this.close(true);
- let signalId = this.connect('closed', () => {
+ const signalId = this.connect('closed', () => {
this.disconnect(signalId);
this._confirmRebootToBootLoaderMenu();
});
}
_startTimer() {
- let startTime = GLib.get_monotonic_time();
+ const startTime = GLib.get_monotonic_time();
this._secondsLeft = this._totalSecondsToStayOpen;
this._timerId = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 1, () => {
- let currentTime = GLib.get_monotonic_time();
- let secondsElapsed = (currentTime - startTime) / 1000000;
+ const currentTime = GLib.get_monotonic_time();
+ const secondsElapsed = (currentTime - startTime) / 1000000;
this._secondsLeft = this._totalSecondsToStayOpen - secondsElapsed;
if (this._secondsLeft > 0) {
return GLib.SOURCE_CONTINUE;
}
- let dialogContent = DialogContent[this._type];
- let button = dialogContent.confirmButtons[dialogContent.confirmButtons.length - 1];
+ const dialogContent = DialogContent[this._type];
+ const button = dialogContent.confirmButtons[dialogContent.confirmButtons.length - 1];
this._confirm(button.signal).catch(logError);
this._timerId = 0;
return;
}
- let app = findAppFromInhibitor(inhibitor);
+ const app = findAppFromInhibitor(inhibitor);
const [flags] = app ? inhibitor.GetFlagsSync() : [0];
if (app && flags & GnomeSession.InhibitFlags.LOGOUT) {
- let [description] = inhibitor.GetReasonSync();
- let listItem = new Dialog.ListSectionItem({
+ const [description] = inhibitor.GetReasonSync();
+ const listItem = new Dialog.ListSectionItem({
icon_actor: app.create_icon_texture(_ITEM_ICON_SIZE),
title: app.get_name(),
description,
const sessions = await this._loginManager.listSessions();
for (const [id_, uid_, userName, seat_, sessionPath] of sessions) {
- let proxy = new LogindSession(Gio.DBus.system, 'org.freedesktop.login1', sessionPath);
+ const proxy = new LogindSession(Gio.DBus.system, 'org.freedesktop.login1', sessionPath);
if (proxy.Class !== 'user')
continue;
};
const nSessions = this._sessions.push(session);
- let userAvatar = new UserWidget.Avatar(session.user, {
+ const userAvatar = new UserWidget.Avatar(session.user, {
iconSize: _ITEM_ICON_SIZE,
});
userAvatar.update();
else
userLabelText = userName;
- let listItem = new Dialog.ListSectionItem({
+ const listItem = new Dialog.ListSectionItem({
icon_actor: userAvatar,
title: userLabelText,
});
}
async OpenAsync(parameters, invocation) {
- let [type, timestamp_, totalSecondsToStayOpen, inhibitorObjectPaths] = parameters;
+ const [type, timestamp_, totalSecondsToStayOpen, inhibitorObjectPaths] = parameters;
this._totalSecondsToStayOpen = totalSecondsToStayOpen;
this._type = type;
return;
}
- let dialogContent = DialogContent[this._type];
+ const dialogContent = DialogContent[this._type];
for (let i = 0; i < inhibitorObjectPaths.length; i++) {
- let inhibitor = new GnomeSession.Inhibitor(inhibitorObjectPaths[i], proxy => {
+ const inhibitor = new GnomeSession.Inhibitor(inhibitorObjectPaths[i], proxy => {
this._onInhibitorLoaded(proxy);
});
if (dialogContent.showOtherSessions)
this._loadSessions().catch(logError);
- let updatesAllowed = this._updatesPermission && this._updatesPermission.allowed;
+ const updatesAllowed = this._updatesPermission && this._updatesPermission.allowed;
_setCheckBoxLabel(this._checkBox, dialogContent.checkBoxText || '');
this._checkBox.visible = dialogContent.checkBoxText && this._updateInfo.UpdatePrepared && updatesAllowed;
this._sync();
- let signalId = this.connect('opened', () => {
+ const signalId = this.connect('opened', () => {
invocation.return_value(null);
this.disconnect(signalId);
});
if (styleProps) {
layoutClass.prototype.hookup_style = function (container) {
container.connect('style-changed', () => {
- let node = container.get_theme_node();
- for (let prop in styleProps) {
- let [found, length] = node.lookup_length(styleProps[prop], false);
+ const node = container.get_theme_node();
+ for (const prop in styleProps) {
+ const [found, length] = node.lookup_length(styleProps[prop], false);
if (found)
this[prop] = length;
}
}
function _makeEaseCallback(params, cleanup) {
- let onComplete = params.onComplete;
+ const onComplete = params.onComplete;
delete params.onComplete;
- let onStopped = params.onStopped;
+ const onStopped = params.onStopped;
delete params.onStopped;
return isFinished => {
if (!propName.startsWith('@'))
return [actor, propName];
- let [type, name, prop] = propName.split('.');
+ const [type, name, prop] = propName.split('.');
switch (type) {
case '@layout':
return [actor.layout_manager, name];
global.compositor.enable_unredirect();
global.end_work();
};
- let callback = _makeEaseCallback(params, cleanup);
+ const callback = _makeEaseCallback(params, cleanup);
// cancel overwritten transitions
- let animatedProps = Object.keys(params).map(p => p.replace('_', '-', 'g'));
+ const animatedProps = Object.keys(params).map(p => p.replace('_', '-', 'g'));
animatedProps.forEach(p => actor.remove_transition(p));
if (actor.get_easing_duration() > 0 || !isReversed)
global.compositor.enable_unredirect();
global.end_work();
};
- let callback = _makeEaseCallback(params, cleanup);
+ const callback = _makeEaseCallback(params, cleanup);
// cancel overwritten transition
actor.remove_transition(propName);
if (duration === 0) {
- let [obj, prop] = _getPropertyTarget(actor, propName);
+ const [obj, prop] = _getPropertyTarget(actor, propName);
if (!isReversed)
obj[prop] = target;
return;
}
- let pspec = actor.find_property(propName);
- let transition = new Clutter.PropertyTransition({
+ const pspec = actor.find_property(propName);
+ const transition = new Clutter.PropertyTransition({
property_name: propName,
interval: new Clutter.Interval({value_type: pspec.value_type}),
remove_on_complete: true,
const origToString = Object.prototype.toString;
Object.prototype.toString = function () {
- let base = origToString.call(this);
+ const base = origToString.call(this);
try {
if ('actor' in this && this.actor instanceof Clutter.Actor)
return base.replace(/\]$/, ` delegate for ${this.actor.toString().substring(1)}`);
const slowdownEnv = GLib.getenv('GNOME_SHELL_SLOWDOWN_FACTOR');
if (slowdownEnv) {
- let factor = parseFloat(slowdownEnv);
+ const factor = parseFloat(slowdownEnv);
if (!isNaN(factor) && factor > 0.0)
St.Settings.get().slow_down_factor = factor;
}
* @param {string} uuid
*/
export function uninstallExtension(uuid) {
- let extension = Main.extensionManager.lookup(uuid);
+ const extension = Main.extensionManager.lookup(uuid);
if (!extension)
return false;
if (!Main.extensionManager.updatesSupported)
return;
- let metadatas = {};
+ const metadatas = {};
Main.extensionManager.getUuids().forEach(uuid => {
- let extension = Main.extensionManager.lookup(uuid);
+ const extension = Main.extensionManager.lookup(uuid);
if (extension.type !== ExtensionUtils.ExtensionType.PER_USER)
return;
if (extension.hasUpdate)
default: true,
}]);
- let content = new Dialog.MessageDialogContent({
+ const content = new Dialog.MessageDialogContent({
title: _('Install Extension'),
description: _('Download and install “%s” from extensions.gnome.org?').format(info.name),
});
// are enabled after start. If it exists, then the systemd unit will
// disable extensions should gnome-shell crash.
// Should the file already exist from a previous login, then this is OK.
- let disableFilename = GLib.build_filenamev([GLib.get_user_runtime_dir(), 'gnome-shell-disable-extensions']);
- let disableFile = Gio.File.new_for_path(disableFilename);
+ const disableFilename = GLib.build_filenamev([GLib.get_user_runtime_dir(), 'gnome-shell-disable-extensions']);
+ const disableFile = Gio.File.new_for_path(disableFilename);
try {
disableFile.create(Gio.FileCreateFlags.REPLACE_DESTINATION, null);
} catch (e) {
}
async _callExtensionDisable(uuid) {
- let extension = this.lookup(uuid);
+ const extension = this.lookup(uuid);
if (!extension)
return;
// user disables C
// this should: disable E, disable D, disable C, enable D, enable E
- let orderIdx = this._extensionOrder.indexOf(uuid);
- let order = this._extensionOrder.slice(orderIdx + 1);
- let orderReversed = order.slice().reverse();
+ const orderIdx = this._extensionOrder.indexOf(uuid);
+ const order = this._extensionOrder.slice(orderIdx + 1);
+ const orderReversed = order.slice().reverse();
for (let i = 0; i < orderReversed.length; i++) {
- let otherUuid = orderReversed[i];
+ const otherUuid = orderReversed[i];
try {
console.debug(`Temporarily disable extension ${otherUuid}`);
this.lookup(otherUuid).stateObj.disable();
this._unloadExtensionStylesheet(extension);
for (let i = 0; i < order.length; i++) {
- let otherUuid = order[i];
+ const otherUuid = order[i];
try {
console.debug(`Re-enable extension ${otherUuid}`);
// eslint-disable-next-line no-await-in-loop
if (!this._extensionSupportsSessionMode(uuid))
return;
- let extension = this.lookup(uuid);
+ const extension = this.lookup(uuid);
if (!extension)
return;
if (!this._extensions.has(uuid))
return false;
- let enabledExtensions = global.settings.get_strv(ENABLED_EXTENSIONS_KEY);
+ const enabledExtensions = global.settings.get_strv(ENABLED_EXTENSIONS_KEY);
let disabledExtensions = global.settings.get_strv(DISABLED_EXTENSIONS_KEY);
if (disabledExtensions.includes(uuid)) {
return false;
let enabledExtensions = global.settings.get_strv(ENABLED_EXTENSIONS_KEY);
- let disabledExtensions = global.settings.get_strv(DISABLED_EXTENSIONS_KEY);
+ const disabledExtensions = global.settings.get_strv(DISABLED_EXTENSIONS_KEY);
if (enabledExtensions.includes(uuid)) {
enabledExtensions = enabledExtensions.filter(item => item !== uuid);
return;
}
- let extension = this.lookup(uuid);
+ const extension = this.lookup(uuid);
if (!extension)
return;
if (!this._updateNotified) {
this._updateNotified = true;
- let source = new ExtensionUpdateSource();
+ const source = new ExtensionUpdateSource();
Main.messageTray.add(source);
const notification = new MessageTray.Notification({
}
logExtensionError(uuid, error) {
- let extension = this.lookup(uuid);
+ const extension = this.lookup(uuid);
if (!extension)
return;
async reloadExtension(oldExtension) {
// Grab the things we'll need to pass to createExtensionObject
// to reload it.
- let {uuid, dir, type} = oldExtension;
+ const {uuid, dir, type} = oldExtension;
// Then unload the old extension.
await this.unloadExtension(oldExtension);
if (!this._extensionSupportsSessionMode(uuid))
return false;
- let extension = this.lookup(uuid);
+ const extension = this.lookup(uuid);
if (!extension)
throw new Error('Extension was not properly created. Call createExtensionObject first');
- let dir = extension.dir;
- let extensionJs = dir.get_child('extension.js');
+ const dir = extension.dir;
+ const extensionJs = dir.get_child('extension.js');
if (!extensionJs.query_exists(null)) {
this.logExtensionError(uuid, new Error('Missing extension.js'));
return false;
}
_updateCanChange(extension) {
- let isMode = this._getModeExtensions().includes(extension.uuid);
- let modeOnly = global.settings.get_boolean(DISABLE_USER_EXTENSIONS_KEY);
+ const isMode = this._getModeExtensions().includes(extension.uuid);
+ const modeOnly = global.settings.get_boolean(DISABLE_USER_EXTENSIONS_KEY);
- let changeKey = isMode
+ const changeKey = isMode
? DISABLE_USER_EXTENSIONS_KEY
: ENABLED_EXTENSIONS_KEY;
extensions.sort((a, b) => this._compareExtensions(this.lookup(a), this.lookup(b)));
// filter out 'disabled-extensions' which takes precedence
- let disabledExtensions = global.settings.get_strv(DISABLED_EXTENSIONS_KEY);
+ const disabledExtensions = global.settings.get_strv(DISABLED_EXTENSIONS_KEY);
return extensions.filter(item => !disabledExtensions.includes(item));
}
}
async _onEnabledExtensionsChanged() {
- let newEnabledExtensions = this._getEnabledExtensions();
+ const newEnabledExtensions = this._getEnabledExtensions();
for (const extension of this._extensions.values()) {
const wasEnabled = extension.enabled;
}
_onSettingsWritableChanged() {
- for (let extension of this._extensions.values()) {
+ for (const extension of this._extensions.values()) {
this._updateCanChange(extension);
this.emit('extension-state-changed', extension);
}
this._checkVersion = checkVersion;
// Disabling extensions modifies the order array, so use a copy
- let extensionOrder = this._extensionOrder.slice();
+ const extensionOrder = this._extensionOrder.slice();
// Disable enabled extensions first to avoid
// the "rebasing" done in _callExtensionDisable...
return;
for (const {file: dir, info} of FileUtils.collectFromDatadirs('extension-updates', true)) {
- let fileType = info.get_file_type();
+ const fileType = info.get_file_type();
if (fileType !== Gio.FileType.DIRECTORY)
continue;
- let uuid = info.get_name();
- let extensionDir = Gio.File.new_for_path(
+ const uuid = info.get_name();
+ const extensionDir = Gio.File.new_for_path(
GLib.build_filenamev([global.userdatadir, 'extensions', uuid]));
try {
this._enabledExtensions = this._getEnabledExtensions();
- let perUserDir = Gio.File.new_for_path(global.userdatadir);
+ const perUserDir = Gio.File.new_for_path(global.userdatadir);
const includeUserDir = global.settings.get_boolean('allow-extension-installation');
const extensionFiles = [...FileUtils.collectFromDatadirs('extensions', includeUserDir)];
const extensionObjects = extensionFiles.map(({file: dir, info}) => {
- let fileType = info.get_file_type();
+ const fileType = info.get_file_type();
if (fileType !== Gio.FileType.DIRECTORY)
return null;
- let uuid = info.get_name();
- let existing = this.lookup(uuid);
+ const uuid = info.get_name();
+ const existing = this.lookup(uuid);
if (existing) {
log(`Extension ${uuid} already installed in ${existing.path}. ${dir.get_path()} will not be loaded`);
return null;
}
let extension;
- let type = dir.has_prefix(perUserDir)
+ const type = dir.has_prefix(perUserDir)
? ExtensionType.PER_USER
: ExtensionType.SYSTEM;
try {
}
_isWithinGrabbedActor(actor) {
- let currentActor = this.currentGrab.actor;
+ const currentActor = this.currentGrab.actor;
while (actor) {
if (actor === currentActor)
return true;
_actorInGrabStack(actor) {
while (actor) {
- let idx = this._findStackIndex(actor);
+ const idx = this._findStackIndex(actor);
if (idx >= 0)
return idx;
actor = actor.get_parent();
onUngrab: null,
});
- let focus = global.stage.key_focus;
- let hadFocus = focus && this._isWithinGrabbedActor(focus);
- let newFocus = params.actor;
+ const focus = global.stage.key_focus;
+ const hadFocus = focus && this._isWithinGrabbedActor(focus);
+ const newFocus = params.actor;
if (this.isActorGrabbed(params.actor))
return true;
}
_takeModalGrab() {
- let firstGrab = this._modalCount === 0;
+ const firstGrab = this._modalCount === 0;
if (firstGrab) {
- let grab = Main.pushModal(this._owner, this._modalParams);
+ const grab = Main.pushModal(this._owner, this._modalParams);
if (grab.get_seat_state() !== Clutter.GrabState.ALL) {
Main.popModal(grab);
return false;
isUser: false,
});
- let grabStackIndex = this._findStackIndex(params.actor);
+ const grabStackIndex = this._findStackIndex(params.actor);
if (grabStackIndex < 0)
return;
- let focus = global.stage.key_focus;
- let hadFocus = focus && this._isWithinGrabbedActor(focus);
+ const focus = global.stage.key_focus;
+ const hadFocus = focus && this._isWithinGrabbedActor(focus);
- let poppedGrabs = this._grabStack.slice(grabStackIndex);
+ const poppedGrabs = this._grabStack.slice(grabStackIndex);
// "Pop" all newly ungrabbed actors off the grab stack
// by truncating the array.
this._grabStack.length = grabStackIndex;
for (let i = poppedGrabs.length - 1; i >= 0; i--) {
- let poppedGrab = poppedGrabs[i];
+ const poppedGrab = poppedGrabs[i];
if (poppedGrab.onUngrab)
poppedGrab.onUngrab(params.isUser);
}
if (hadFocus) {
- let poppedGrab = poppedGrabs[0];
+ const poppedGrab = poppedGrabs[0];
if (poppedGrab.savedFocus)
poppedGrab.savedFocus.grab_key_focus();
}
}
onCapturedEvent(event) {
- let type = event.type();
+ const type = event.type();
if (type === Clutter.EventType.KEY_PRESS &&
event.get_key_symbol() === Clutter.KEY_Escape) {
return Clutter.EVENT_STOP;
}
- let motion = type === Clutter.EventType.MOTION;
- let press = type === Clutter.EventType.BUTTON_PRESS;
- let release = type === Clutter.EventType.BUTTON_RELEASE;
- let button = press || release;
+ const motion = type === Clutter.EventType.MOTION;
+ const press = type === Clutter.EventType.BUTTON_PRESS;
+ const release = type === Clutter.EventType.BUTTON_RELEASE;
+ const button = press || release;
- let touchUpdate = type === Clutter.EventType.TOUCH_UPDATE;
- let touchBegin = type === Clutter.EventType.TOUCH_BEGIN;
- let touchEnd = type === Clutter.EventType.TOUCH_END;
- let touch = touchUpdate || touchBegin || touchEnd;
+ const touchUpdate = type === Clutter.EventType.TOUCH_UPDATE;
+ const touchBegin = type === Clutter.EventType.TOUCH_BEGIN;
+ const touchEnd = type === Clutter.EventType.TOUCH_END;
+ const touch = touchUpdate || touchBegin || touchEnd;
if (touch && !global.display.is_pointer_emulating_sequence(event.get_event_sequence()))
return Clutter.EVENT_PROPAGATE;
if (press || touchBegin)
this._ignoreUntilRelease = true;
- let i = this._actorInGrabStack(targetActor) + 1;
+ const i = this._actorInGrabStack(targetActor) + 1;
this.ungrab({actor: this._grabStack[i].actor, isUser: true});
return Clutter.EVENT_STOP;
}
this._candidateBoxes.push(box);
this.add_child(box);
- let j = i;
+ const j = i;
box.connect('button-release-event', (actor, event) => {
this.emit('candidate-clicked', j, event.get_button(), event.get_state());
return Clutter.EVENT_PROPAGATE;
setCandidates(indexes, candidates, cursorPosition, cursorVisible) {
for (let i = 0; i < MAX_CANDIDATES_PER_PAGE; ++i) {
- let visible = i < candidates.length;
- let box = this._candidateBoxes[i];
+ const visible = i < candidates.length;
+ const box = this._candidateBoxes[i];
box.visible = visible;
if (!visible)
this._preeditText.text = text.get_text();
- let attrs = text.get_attributes();
+ const attrs = text.get_attributes();
if (attrs)
this._setTextAttributes(this._preeditText.clutter_text, attrs);
});
this._candidateArea.visible = visible;
this._updateVisibility();
- let nCandidates = lookupTable.get_number_of_candidates();
- let cursorPos = lookupTable.get_cursor_pos();
- let pageSize = lookupTable.get_page_size();
- let nPages = Math.ceil(nCandidates / pageSize);
- let page = cursorPos === 0 ? 0 : Math.floor(cursorPos / pageSize);
- let startIndex = page * pageSize;
- let endIndex = Math.min((page + 1) * pageSize, nCandidates);
+ const nCandidates = lookupTable.get_number_of_candidates();
+ const cursorPos = lookupTable.get_cursor_pos();
+ const pageSize = lookupTable.get_page_size();
+ const nPages = Math.ceil(nCandidates / pageSize);
+ const page = cursorPos === 0 ? 0 : Math.floor(cursorPos / pageSize);
+ const startIndex = page * pageSize;
+ const endIndex = Math.min((page + 1) * pageSize, nCandidates);
- let indexes = [];
+ const indexes = [];
let indexLabel;
for (let i = 0; (indexLabel = lookupTable.get_label(i)); ++i)
indexes.push(indexLabel.get_text());
Main.keyboard.resetSuggestions();
Main.keyboard.setSuggestionsVisible(visible);
- let candidates = [];
+ const candidates = [];
for (let i = startIndex; i < endIndex; ++i) {
candidates.push(lookupTable.get_candidate(i).get_text());
Main.keyboard.addSuggestion(lookupTable.get_candidate(i).get_text(), () => {
- let index = i;
+ const index = i;
this._panelService.candidate_clicked(index, 1, 0);
});
}
}
_updateVisibility() {
- let isVisible = !Main.keyboard.visible &&
+ const isVisible = !Main.keyboard.visible &&
(this._preeditText.visible ||
this._auxText.visible ||
this._candidateArea.visible);
this.icon = null;
- let cache = St.TextureCache.get_default();
+ const cache = St.TextureCache.get_default();
cache.connectObject(
'icon-theme-changed', this._onIconThemeChanged.bind(this), this);
}
vfunc_style_changed() {
super.vfunc_style_changed();
- let node = this.get_theme_node();
+ const node = this.get_theme_node();
let size;
if (this._setSizeManually) {
const {scaleFactor} =
St.ThemeContext.get_for_stage(global.stage);
- let [found, len] = node.lookup_length('icon-size', false);
+ const [found, len] = node.lookup_length('icon-size', false);
size = found ? len / scaleFactor : ICON_SIZE;
}
* @param {Clutter.Actor} actor
*/
export function zoomOutActor(actor) {
- let [x, y] = actor.get_transformed_position();
+ const [x, y] = actor.get_transformed_position();
zoomOutActorAtPos(actor, x, y);
}
source: actor,
reactive: false,
});
- let [width, height] = actor.get_transformed_size();
+ const [width, height] = actor.get_transformed_size();
actorClone.set_size(width, height);
actorClone.set_position(x, y);
Main.uiGroup.add_child(actorClone);
// Avoid monitor edges to not zoom outside the current monitor
- let scaledWidth = width * APPICON_ANIMATION_OUT_SCALE;
- let scaledHeight = height * APPICON_ANIMATION_OUT_SCALE;
- let scaledX = x - (scaledWidth - width) / 2;
- let scaledY = y - (scaledHeight - height) / 2;
- let containedX = Math.clamp(scaledX, monitor.x, monitor.x + monitor.width - scaledWidth);
- let containedY = Math.clamp(scaledY, monitor.y, monitor.y + monitor.height - scaledHeight);
+ const scaledWidth = width * APPICON_ANIMATION_OUT_SCALE;
+ const scaledHeight = height * APPICON_ANIMATION_OUT_SCALE;
+ const scaledX = x - (scaledWidth - width) / 2;
+ const scaledY = y - (scaledHeight - height) / 2;
+ const containedX = Math.clamp(scaledX, monitor.x, monitor.x + monitor.width - scaledWidth);
+ const containedY = Math.clamp(scaledY, monitor.y, monitor.y + monitor.height - scaledHeight);
actorClone.ease({
scale_x: APPICON_ANIMATION_OUT_SCALE,
let closestRatio = Infinity;
let bestMode = -1;
- for (let modeIndex in this._gridModes) {
+ for (const modeIndex in this._gridModes) {
const mode = this._gridModes[modeIndex];
const modeRatio = mode.columns / mode.rows;
}
get _app() {
- let windowTracker = Shell.WindowTracker.get_default();
+ const windowTracker = Shell.WindowTracker.get_default();
return windowTracker.get_window_app(this._window);
}
_buildLayout() {
const name = this._app?.get_name() ?? this._window.title;
- let content = new Dialog.MessageDialogContent({
+ const content = new Dialog.MessageDialogContent({
title: _('Allow inhibiting shortcuts'),
description: name
/* Translators: %s is an application name like "Settings" */
const restoreAccel = Meta.prefs_get_keybinding_label('restore-shortcuts');
if (restoreAccel) {
- let restoreLabel = new St.Label({
+ const restoreLabel = new St.Label({
/* Translators: %s is a keyboard shortcut like "Super+x" */
text: _('You can restore shortcuts by pressing %s').format(restoreAccel),
style_class: 'message-dialog-description',
}
/* Check with the permission store */
- let appId = this._app.get_id();
+ const appId = this._app.get_id();
this._permStore = new PermissionStore.PermissionStore(async (proxy, error) => {
if (error) {
log(error.message);
}
_showKbdA11yDialog(seat, newFlags, whatChanged) {
- let dialog = new ModalDialog.ModalDialog();
+ const dialog = new ModalDialog.ModalDialog();
let title, description;
let key, enabled;
return;
}
- let content = new Dialog.MessageDialogContent({title, description});
+ const content = new Dialog.MessageDialogContent({title, description});
dialog.contentLayout.add_child(content);
dialog.addButton({
vfunc_allocate(box) {
if (box.get_width() > 0 && box.get_height() > 0) {
- let sizeRatio = box.get_width() / box.get_height();
+ const sizeRatio = box.get_width() / box.get_height();
if (sizeRatio >= this._ratio) {
/* Restrict horizontally */
- let width = box.get_height() * this._ratio;
- let diff = box.get_width() - width;
+ const width = box.get_height() * this._ratio;
+ const diff = box.get_width() - width;
box.x1 += Math.floor(diff / 2);
box.x2 -= Math.ceil(diff / 2);
}
add(word, callback) {
- let button = new St.Button({label: word});
+ const button = new St.Button({label: word});
button.connect('button-press-event', () => {
callback();
return Clutter.EVENT_STOP;
constructor(actor) {
super(actor, 0.5, St.Side.BOTTOM);
- let inputSourceManager = InputSourceManager.getInputSourceManager();
- let inputSources = inputSourceManager.inputSources;
+ const inputSourceManager = InputSourceManager.getInputSourceManager();
+ const inputSources = inputSourceManager.inputSources;
let item;
- for (let i in inputSources) {
- let is = inputSources[i];
+ for (const i in inputSources) {
+ const is = inputSources[i];
item = this.addAction(is.displayName, () => {
inputSourceManager.activateInputSource(is, true);
}
_onCapturedEvent(actor, event) {
- let type = event.type();
- let press = type === Clutter.EventType.BUTTON_PRESS || type === Clutter.EventType.TOUCH_BEGIN;
- let release = type === Clutter.EventType.BUTTON_RELEASE || type === Clutter.EventType.TOUCH_END;
+ const type = event.type();
+ const press = type === Clutter.EventType.BUTTON_PRESS || type === Clutter.EventType.TOUCH_BEGIN;
+ const release = type === Clutter.EventType.BUTTON_RELEASE || type === Clutter.EventType.TOUCH_END;
const targetActor = global.stage.get_event_actor(event);
if (targetActor === this._boxPointer.bin ||
}
_makeKey(commitString, label, icon) {
- let button = new St.Button({
+ const button = new St.Button({
style_class: 'keyboard-key',
x_expand: true,
});
orientation: Clutter.Orientation.HORIZONTAL,
});
for (let i = 0; i < this._extendedKeys.length; ++i) {
- let extendedKey = this._extendedKeys[i];
- let key = this._makeKey(extendedKey);
+ const extendedKey = this._extendedKeys[i];
+ const key = this._makeKey(extendedKey);
key.extendedKey = extendedKey;
this._extendedKeyboard.add_child(key);
_loadModel(groupName) {
const file = Gio.File.new_for_uri(
`resource:///org/gnome/shell/osk-layouts/${groupName}.json`);
- let [success_, contents] = file.load_contents(null);
+ const [success_, contents] = file.load_contents(null);
const decoder = new TextDecoder();
return JSON.parse(decoder.decode(contents));
this._delta = value;
this.notify('delta');
- let followingPage = this.getFollowingPage();
+ const followingPage = this.getFollowingPage();
if (this._followingPage !== followingPage) {
if (this._followingPanel) {
this._pages = [];
for (let i = 0; i < this._sections.length; i++) {
- let section = this._sections[i];
- let itemsPerPage = this._nCols * this._nRows;
- let nPages = Math.ceil(section.keys.length / itemsPerPage);
+ const section = this._sections[i];
+ const itemsPerPage = this._nCols * this._nRows;
+ const nPages = Math.ceil(section.keys.length / itemsPerPage);
let page = -1;
let pageKeys;
_lookupSection(section, nPage) {
for (let i = 0; i < this._pages.length; i++) {
- let page = this._pages[i];
+ const page = this._pages[i];
if (page.section === section && page.page === nPage)
return i;
/* Set an expander actor so all proportions are right despite the panel
* not having all rows/cols filled in.
*/
- let expander = new Clutter.Actor();
+ const expander = new Clutter.Actor();
gridLayout.attach(expander, 0, 0, this._nCols, this._nRows);
- let page = this._pages[nPage];
+ const page = this._pages[nPage];
let col = 0;
let row = 0;
for (let i = 0; i < page.pageKeys.length; i++) {
- let modelKey = page.pageKeys[i];
- let key = new Key({commitString: modelKey.label}, modelKey.variants);
+ const modelKey = page.pageKeys[i];
+ const key = new Key({commitString: modelKey.label}, modelKey.variants);
key.keyButton.set_button_mask(0);
this.add_child(this._panel);
}
- let page = this._pages[nPage];
+ const page = this._pages[nPage];
this.emit('page-changed', page.section.label, page.page, page.nPages);
}
setCurrentSection(section, nPage) {
for (let i = 0; i < this._pages.length; i++) {
- let page = this._pages[i];
+ const page = this._pages[i];
if (page.section === section && page.page === nPage) {
this.setCurrentPage(i);
this._updateIndicatorPosition();
for (let i = 0; i < this._sections.length; i++) {
- let sect = this._sections[i];
+ const sect = this._sections[i];
sect.button.setLatched(sectionLabel === sect.label);
}
}
}
_populateSections() {
- let file = Gio.File.new_for_uri('resource:///org/gnome/shell/osk-layouts/emoji.json');
- let [success_, contents] = file.load_contents(null);
+ const file = Gio.File.new_for_uri('resource:///org/gnome/shell/osk-layouts/emoji.json');
+ const [success_, contents] = file.load_contents(null);
- let emoji = JSON.parse(new TextDecoder().decode(contents));
+ const emoji = JSON.parse(new TextDecoder().decode(contents));
let variants = [];
let currentKey = 0;
continue;
}
- let newSection = this._findSection(emoji[currentKey].name);
+ const newSection = this._findSection(emoji[currentKey].name);
if (newSection != null) {
currentSection = newSection;
currentSection.keys = [];
}
/* Create the key */
- let label = emoji[currentKey].char + String.fromCharCode(0xFE0F);
+ const label = emoji[currentKey].char + String.fromCharCode(0xFE0F);
currentSection.keys.push({label, variants});
currentKey = i;
variants = [];
}
_createBottomRow() {
- let row = new KeyContainer();
+ const row = new KeyContainer();
let key;
row.appendRow();
row.appendKey(key, 1.5);
for (let i = 0; i < this._sections.length; i++) {
- let section = this._sections[i];
+ const section = this._sections[i];
key = new Key({label: section.label}, []);
key.connect('released', () => this._emojiPager.setCurrentSection(section, 0));
if (!this._lastDevice)
return false;
- let deviceType = this._lastDevice.get_device_type();
+ const deviceType = this._lastDevice.get_device_type();
return deviceType === Clutter.InputDeviceType.TOUCHSCREEN_DEVICE;
}
_syncEnabled() {
- let enableKeyboard = this._a11yApplicationsSettings.get_boolean(SHOW_KEYBOARD);
- let autoEnabled = this._seat.get_touch_mode() && this._lastDeviceIsTouchscreen();
- let enabled = enableKeyboard || autoEnabled;
+ const enableKeyboard = this._a11yApplicationsSettings.get_boolean(SHOW_KEYBOARD);
+ const autoEnabled = this._seat.get_touch_mode() && this._lastDeviceIsTouchscreen();
+ const enabled = enableKeyboard || autoEnabled;
if (!enabled && !this._keyboard)
return;
}
_onFocusPositionChanged(focusTracker) {
- let rect = focusTracker.getCurrentRect();
+ const rect = focusTracker.getCurrentRect();
this.setCursorLocation(focusTracker.currentWindow, rect.x, rect.y, rect.width, rect.height);
this._updateLevelFromHints(true);
}
}
_onKeyFocusChanged() {
- let focus = global.stage.key_focus;
+ const focus = global.stage.key_focus;
// Showing an extended key popup and clicking a key from the extended keys
// will grab focus, but ignore that
- let extendedKeysWereFocused = this._focusInExtendedKeys;
+ const extendedKeysWereFocused = this._focusInExtendedKeys;
this._focusInExtendedKeys = focus && (focus._extendedKeys || focus.extendedKey);
if (this._focusInExtendedKeys || extendedKeysWereFocused)
return;
_updateLayout(groupName, purpose) {
let keyboardModel = null;
- let layers = {};
- let layout = new Clutter.Actor({
+ const layers = {};
+ const layout = new Clutter.Actor({
layout_manager: new Clutter.BinLayout(),
x_expand: true,
y_expand: true,
purpose === Clutter.InputContentPurpose.TERMINAL);
keyboardModel.getLevels().forEach(currentLevel => {
- let levelLayout = new KeyContainer();
+ const levelLayout = new KeyContainer();
levelLayout.shiftKeys = [];
levelLayout.mode = currentLevel.mode;
accumulatedWidth = 0;
}
- let button = new Key({
+ const button = new Key({
commitString,
label: key.label,
iconName: key.iconName,
}
if (key.action === 'modifier') {
- let modifierKeys = this._modifierKeys[key.keyval] || [];
+ const modifierKeys = this._modifierKeys[key.keyval] || [];
modifierKeys.push(button);
this._modifierKeys[key.keyval] = modifierKeys;
}
_setCurrentLevelLatched(layout, latched) {
for (let i = 0; i < layout.shiftKeys.length; i++) {
- let key = layout.shiftKeys[i];
+ const key = layout.shiftKeys[i];
key.setLatched(latched);
key.iconName = latched
? 'osk-caps-lock-symbolic' : 'osk-shift-symbolic';
}
_getGridSlots() {
- let numOfHorizSlots = 0, numOfVertSlots;
- let rows = this._currentPage.get_children();
- numOfVertSlots = rows.length;
+ let numOfHorizSlots = 0;
+ const rows = this._currentPage.get_children();
+ const numOfVertSlots = rows.length;
for (let i = 0; i < rows.length; ++i) {
- let keyboardRow = rows[i];
- let keys = keyboardRow.get_children();
+ const keyboardRow = rows[i];
+ const keys = keyboardRow.get_children();
numOfHorizSlots = Math.max(numOfHorizSlots, keys.length);
}
}
_relayout() {
- let monitor = Main.layoutManager.keyboardMonitor;
+ const monitor = Main.layoutManager.keyboardMonitor;
if (!monitor)
return;
_setActiveLevel(activeLevel) {
const layers = this._layers;
- let currentPage = layers[activeLevel];
+ const currentPage = layers[activeLevel];
if (this._currentPage === currentPage) {
this._updateCurrentPageVisible();
}
_animateShowComplete() {
- let keyboardBox = Main.layoutManager.keyboardBox;
+ const keyboardBox = Main.layoutManager.keyboardBox;
this._keyboardHeightNotifyId = keyboardBox.connect('notify::height', () => {
this.translation_y = -this.height;
});
gestureProgress(delta) {
this._gestureInProgress = true;
Main.layoutManager.keyboardBox.show();
- let progress = Math.min(delta, this.height) / this.height;
+ const progress = Math.min(delta, this.height) / this.height;
this.translation_y = -this.height * progress;
this.opacity = 255 * progress;
const windowActor = this._focusWindow?.get_compositor_private();
}
_animateWindow(window, show) {
- let windowActor = window.get_compositor_private();
+ const windowActor = window.get_compositor_private();
if (!windowActor)
return;
}
setCursorLocation(window, x, y, w, h) {
- let monitor = Main.layoutManager.keyboardMonitor;
+ const monitor = Main.layoutManager.keyboardMonitor;
if (window && monitor) {
const keyboardHeight = Main.layoutManager.keyboardBox.height;
constructor() {
super();
- let seat = global.stage.context.get_backend().get_default_seat();
+ const seat = global.stage.context.get_backend().get_default_seat();
this._virtualDevice = seat.create_virtual_device(Clutter.InputDeviceType.KEYBOARD_DEVICE);
this._inputSourceManager = InputSourceManager.getInputSourceManager();
}
_onSourceChanged(inputSourceManager, _oldSource) {
- let source = inputSourceManager.currentSource;
+ const source = inputSourceManager.currentSource;
this._currentSource = source;
this.emit('group-changed');
}
}
if (enabled) {
- let func = (text, cursor, anchor) => {
+ const func = (text, cursor, anchor) => {
if (cursor === 0 && anchor === 0)
return;
this._surroundingUpdateId = Main.inputMethod.connect(
'surrounding-text-set', () => {
- let [text, cursor, anchor] = Main.inputMethod.getSurroundingText();
+ const [text, cursor, anchor] = Main.inputMethod.getSurroundingText();
if (this._timesDeleted === 0) {
func(text, cursor, anchor);
} else {
}
});
- let [text, cursor, anchor] = Main.inputMethod.getSurroundingText();
+ const [text, cursor, anchor] = Main.inputMethod.getSurroundingText();
if (text)
func(text, cursor, anchor);
else
let rect;
if (this._workArea) {
- let workspaceManager = global.workspace_manager;
- let ws = workspaceManager.get_workspace_by_index(0);
+ const workspaceManager = global.workspace_manager;
+ const ws = workspaceManager.get_workspace_by_index(0);
rect = ws.get_work_area_for_monitor(index);
} else {
rect = Main.layoutManager.monitors[index];
const UiActor = GObject.registerClass(
class UiActor extends St.Widget {
vfunc_get_preferred_width(_forHeight) {
- let width = global.stage.width;
+ const width = global.stage.width;
return [width, width];
}
vfunc_get_preferred_height(_forWidth) {
- let height = global.stage.height;
+ const height = global.stage.height;
return [height, height];
}
});
global.compositor.get_feedback_group(),
];
- for (let adoptedActor of adoptedUiGroupActors) {
+ for (const adoptedActor of adoptedUiGroupActors) {
this.uiGroup.remove_child(adoptedActor);
global.stage.add_child(adoptedActor);
}
this._updateHotCorners.bind(this));
// Need to update struts on new workspaces when they are added
- let workspaceManager = global.workspace_manager;
+ const workspaceManager = global.workspace_manager;
workspaceManager.connect('notify::n-workspaces',
this._queueUpdateRegions.bind(this));
- let display = global.display;
+ const display = global.display;
display.connect('restacked',
this._windowsRestacked.bind(this));
display.connect('in-fullscreen-changed',
}
_updateMonitors() {
- let display = global.display;
+ const display = global.display;
this.monitors = [];
- let nMonitors = display.get_n_monitors();
+ const nMonitors = display.get_n_monitors();
for (let i = 0; i < nMonitors; i++) {
this.monitors.push(new Monitor(i,
display.get_monitor_geometry(i),
// to split primary from bottom.
this.primaryIndex = this.bottomIndex = display.get_primary_monitor();
for (let i = 0; i < this.monitors.length; i++) {
- let monitor = this.monitors[i];
+ const monitor = this.monitors[i];
if (this._isAboveOrBelowPrimary(monitor)) {
if (monitor.y > this.monitors[this.bottomIndex].y)
this.bottomIndex = i;
return;
}
- let size = this.panelBox.height;
+ const size = this.panelBox.height;
// build new hot corners
for (let i = 0; i < this.monitors.length; i++) {
- let monitor = this.monitors[i];
- let cornerX = this._rtl ? monitor.x + monitor.width : monitor.x;
- let cornerY = monitor.y;
+ const monitor = this.monitors[i];
+ const cornerX = this._rtl ? monitor.x + monitor.width : monitor.x;
+ const cornerY = monitor.y;
let haveTopLeftCorner = true;
if (i !== this.primaryIndex) {
// Check if we have a top left (right for RTL) corner.
// I.e. if there is no monitor directly above or to the left(right)
- let besideX = this._rtl ? monitor.x + 1 : cornerX - 1;
- let besideY = cornerY;
- let aboveX = cornerX;
- let aboveY = cornerY - 1;
+ const besideX = this._rtl ? monitor.x + 1 : cornerX - 1;
+ const besideY = cornerY;
+ const aboveX = cornerX;
+ const aboveY = cornerY - 1;
for (let j = 0; j < this.monitors.length; j++) {
if (i === j)
continue;
- let otherMonitor = this.monitors[j];
+ const otherMonitor = this.monitors[j];
if (besideX >= otherMonitor.x &&
besideX < otherMonitor.x + otherMonitor.width &&
besideY >= otherMonitor.y &&
}
if (haveTopLeftCorner) {
- let corner = new HotCorner(this, monitor, cornerX, cornerY);
+ const corner = new HotCorner(this, monitor, cornerX, cornerY);
corner.setBarrierSize(size);
this.hotCorners.push(corner);
} else {
_showSecondaryBackgrounds() {
for (let i = 0; i < this.monitors.length; i++) {
if (i !== this.primaryIndex) {
- let backgroundActor = this._bgManagers[i].backgroundActor;
+ const backgroundActor = this._bgManagers[i].backgroundActor;
backgroundActor.show();
backgroundActor.opacity = 0;
backgroundActor.ease({
return Promise.resolve();
for (let i = 0; i < this.monitors.length; i++) {
- let bgManager = this._createBackgroundManager(i);
+ const bgManager = this._createBackgroundManager(i);
this._bgManagers.push(bgManager);
if (i !== this.primaryIndex && this._startingUp)
_panelBoxChanged() {
this._updatePanelBarrier();
- let size = this.panelBox.height;
+ const size = this.panelBox.height;
this.hotCorners.forEach(corner => {
if (corner)
corner.setBarrierSize(size);
return;
if (this.panelBox.height) {
- let primary = this.primaryMonitor;
+ const primary = this.primaryMonitor;
this._rightPanelBarrier = new Meta.Barrier({
backend: global.backend,
}
_isAboveOrBelowPrimary(monitor) {
- let primary = this.monitors[this.primaryIndex];
- let monitorLeft = monitor.x, monitorRight = monitor.x + monitor.width;
- let primaryLeft = primary.x, primaryRight = primary.x + primary.width;
+ const primary = this.monitors[this.primaryIndex];
+ const monitorLeft = monitor.x, monitorRight = monitor.x + monitor.width;
+ const primaryLeft = primary.x, primaryRight = primary.x + primary.width;
if ((monitorLeft >= primaryLeft && monitorLeft < primaryRight) ||
(monitorRight > primaryLeft && monitorRight <= primaryRight) ||
}
get currentMonitor() {
- let index = global.display.get_current_monitor();
+ const index = global.display.get_current_monitor();
return this.monitors[index];
}
});
this._systemBackground.add_constraint(constraint);
- let signalId = this._systemBackground.connect('loaded', () => {
+ const signalId = this._systemBackground.connect('loaded', () => {
this._systemBackground.disconnect(signalId);
// We're mostly prepared for the startup animation
} else {
this.keyboardBox.hide();
- let monitor = this.primaryMonitor;
+ const monitor = this.primaryMonitor;
if (!Main.sessionMode.hasOverview) {
const x = monitor.x + monitor.width / 2.0;
index = this._findActor(ancestor);
}
- let ancestorData = ancestor
+ const ancestorData = ancestor
? this._trackedActors[index]
: defaultParams;
// We can't use Params.parse here because we want to drop
// the extra values like ancestorData.actor
- for (let prop in defaultParams) {
+ for (const prop in defaultParams) {
if (!Object.prototype.hasOwnProperty.call(params, prop))
params[prop] = ancestorData[prop];
}
_findActor(actor) {
for (let i = 0; i < this._trackedActors.length; i++) {
- let actorData = this._trackedActors[i];
+ const actorData = this._trackedActors[i];
if (actorData.actor === actor)
return i;
}
if (this._findActor(actor) !== -1)
throw new Error('trying to re-track existing chrome actor');
- let actorData = Params.parse(params, defaultParams);
+ const actorData = Params.parse(params, defaultParams);
actorData.actor = actor;
actor.connectObject(
'notify::visible', this._queueUpdateRegions.bind(this),
}
_untrackActor(actor) {
- let i = this._findActor(actor);
+ const i = this._findActor(actor);
if (i === -1)
return;
if (!actorData.trackFullscreen)
return;
- let monitor = this.findMonitorForActor(actorData.actor);
+ const monitor = this.findMonitorForActor(actorData.actor);
actorData.actor.visible = !(global.window_group.visible &&
monitor &&
monitor.inFullscreen);
}
_updateVisibility() {
- let windowsVisible = Main.sessionMode.hasWindows && !this._inOverview;
+ const windowsVisible = Main.sessionMode.hasWindows && !this._inOverview;
global.window_group.visible = windowsVisible;
global.top_window_group.visible = windowsVisible;
getWorkAreaForMonitor(monitorIndex) {
// Assume that all workspaces will have the same
// struts and pick the first one.
- let workspaceManager = global.workspace_manager;
- let ws = workspaceManager.get_workspace_by_index(0);
+ const workspaceManager = global.workspace_manager;
+ const ws = workspaceManager.get_workspace_by_index(0);
return ws.get_work_area_for_monitor(monitorIndex);
}
// This call guarantees that we return some monitor to simplify usage of it
// In practice all tracked actors should be visible on some monitor anyway
findIndexForActor(actor) {
- let [x, y] = actor.get_transformed_position();
- let [w, h] = actor.get_transformed_size();
+ const [x, y] = actor.get_transformed_position();
+ const [w, h] = actor.get_transformed_size();
return this._findIndexForRect(x, y, w, h);
}
delete this._updateRegionIdle;
}
- let rects = [], struts = [], i;
- let isPopupMenuVisible = global.top_window_group.get_children().some(isPopupMetaWindow);
+ const rects = [], struts = [];
+ const isPopupMenuVisible = global.top_window_group.get_children().some(isPopupMetaWindow);
const wantsInputRegion =
!this._startingUp &&
!isPopupMenuVisible &&
Main.modalCount === 0 &&
!Meta.is_wayland_compositor();
- for (i = 0; i < this._trackedActors.length; i++) {
- let actorData = this._trackedActors[i];
+ for (let i = 0; i < this._trackedActors.length; i++) {
+ const actorData = this._trackedActors[i];
if (!(actorData.affectsInputRegion && wantsInputRegion) && !actorData.affectsStruts)
continue;
if (monitor) {
// Limit struts to the size of the screen
- let x1 = Math.max(x, 0);
- let x2 = Math.min(x + w, global.screen_width);
- let y1 = Math.max(y, 0);
- let y2 = Math.min(y + h, global.screen_height);
+ const x1 = Math.max(x, 0);
+ const x2 = Math.min(x + w, global.screen_width);
+ const y1 = Math.max(y, 0);
+ const y2 = Math.min(y + h, global.screen_height);
// Metacity wants to know what side of the monitor the
// strut is considered to be attached to. First, we find
}
const strutRect = new Mtk.Rectangle({x: x1, y: y1, width: x2 - x1, height: y2 - y1});
- let strut = new Meta.Strut({rect: strutRect, side});
+ const strut = new Meta.Strut({rect: strutRect, side});
struts.push(strut);
}
}
this._isPopupWindowVisible = isPopupMenuVisible;
- let workspaceManager = global.workspace_manager;
+ const workspaceManager = global.workspace_manager;
for (let w = 0; w < workspaceManager.n_workspaces; w++) {
- let workspace = workspaceManager.get_workspace_by_index(w);
+ const workspace = workspaceManager.get_workspace_by_index(w);
workspace.set_builtin_struts(struts);
}
// oldest to newest, so just look for the first old event,
// and then chop events after that off.
let i = 0;
- let threshold = this._lastTime - this._timeout;
+ const threshold = this._lastTime - this._timeout;
while (i < this._barrierEvents.length) {
- let [time, distance_] = this._barrierEvents[i];
+ const [time, distance_] = this._barrierEvents[i];
if (time >= threshold)
break;
i++;
}
- let firstNewEvent = i;
+ const firstNewEvent = i;
for (i = 0; i < firstNewEvent; i++) {
- let [time_, distance] = this._barrierEvents[i];
+ const [time_, distance] = this._barrierEvents[i];
this._currentPressure -= distance;
}
if (!(this._actionMode & Main.actionMode))
return;
- let slide = this._getDistanceAlongBarrier(barrier, event);
+ const slide = this._getDistanceAlongBarrier(barrier, event);
let distance = this._getDistanceAcrossBarrier(barrier, event);
if (distance >= this._threshold) {
}
_childAdded(container, newChild) {
- let children = this._container.get_children();
- let myIndex = children.indexOf(this);
- let newChildIndex = children.indexOf(newChild);
+ const children = this._container.get_children();
+ const myIndex = children.indexOf(this);
+ const newChildIndex = children.indexOf(newChild);
if (newChildIndex > myIndex) {
// The child was added above the shade (presumably it was
this._children.unshift(newChild);
} else {
// Somewhere else; insert it into the correct spot
- let prevChild = this._children.indexOf(children[newChildIndex - 1]);
+ const prevChild = this._children.indexOf(children[newChildIndex - 1]);
if (prevChild !== -1) // paranoia
this._children.splice(prevChild + 1, 0, newChild);
}
lightOn(fadeInTime) {
this.remove_all_transitions();
- let easeProps = {
+ const easeProps = {
duration: fadeInTime || 0,
mode: Clutter.AnimationMode.EASE_OUT_QUAD,
};
- let onComplete = () => {
+ const onComplete = () => {
this._active = true;
this.notify('active');
};
this._active = false;
this.notify('active');
- let easeProps = {
+ const easeProps = {
duration: fadeOutTime || 0,
mode: Clutter.AnimationMode.EASE_OUT_QUAD,
};
- let onComplete = () => this.hide();
+ const onComplete = () => this.hide();
if (this._radialEffect) {
this.ease_property(
}
_childRemoved(container, child) {
- let index = this._children.indexOf(child);
+ const index = this._children.indexOf(child);
if (index !== -1) // paranoia
this._children.splice(index, 1);
}
_syncEnabled() {
- let enabled = this._settings.get_boolean(LOCATE_POINTER_KEY);
+ const enabled = this._settings.get_boolean(LOCATE_POINTER_KEY);
if (enabled === !!this._ripples)
return;
if (!this._ripples)
return;
- let [x, y] = global.get_pointer();
+ const [x, y] = global.get_pointer();
this._ripples.playAnimation(x, y);
}
}
this.additionalCompletionText(event.completions[0], event.attrHead);
this.emit('completion', {completion: event.completions[0], type: 'whole-word'});
} else if (event.completions.length > 1 && event.tabType === 'single') {
- let commonPrefix = JsParse.getCommonPrefix(event.completions);
+ const commonPrefix = JsParse.getCommonPrefix(event.completions);
if (commonPrefix.length > 0) {
this.additionalCompletionText(commonPrefix, event.attrHead);
}
_entryKeyPressEvent(actor, event) {
- let cursorPos = this._entry.clutter_text.get_cursor_position();
+ const cursorPos = this._entry.clutter_text.get_cursor_position();
let text = this._entry.get_text();
if (cursorPos !== -1)
text = text.slice(0, cursorPos);
// Insert characters of text not already included in head at cursor position. i.e., if text="abc" and head="a",
// the string "bc" will be appended to this._entry
additionalCompletionText(text, head) {
- let additionalCompletionText = text.slice(head.length);
- let cursorPos = this._entry.clutter_text.get_cursor_position();
+ const additionalCompletionText = text.slice(head.length);
+ const cursorPos = this._entry.clutter_text.get_cursor_position();
this._entry.clutter_text.insert_text(additionalCompletionText, cursorPos);
}
reactive: true,
track_hover: true,
});
- let label = new St.Button({label: name});
+ const label = new St.Button({label: name});
label.connect('clicked', () => {
this.selectChild(child);
return true;
_unselect() {
if (this._selectedIndex < 0)
return;
- let tabData = this._tabs[this._selectedIndex];
+ const tabData = this._tabs[this._selectedIndex];
tabData.labelBox.remove_style_pseudo_class('selected');
tabData.scrollView.hide();
this._selectedIndex = -1;
}
// Focus the new tab before unmapping the old one
- let tabData = this._tabs[index];
+ const tabData = this._tabs[index];
if (!tabData.scrollView.navigate_focus(null, St.DirectionType.TAB_FORWARD, false))
this.grab_key_focus();
this.selectIndex(-1);
} else {
for (let i = 0; i < this._tabs.length; i++) {
- let tabData = this._tabs[i];
+ const tabData = this._tabs[i];
if (tabData.child === child) {
this.selectIndex(i);
return;
}
scrollToBottom(index) {
- let tabData = this._tabs[index];
+ const tabData = this._tabs[index];
tabData._scrollToBottom = true;
}
this._lookingGlass = lookingGlass;
- let cmdTxt = new St.Label({text: command});
+ const cmdTxt = new St.Label({text: command});
cmdTxt.clutter_text.ellipsize = Pango.EllipsizeMode.END;
this.add_child(cmdTxt);
- let box = new St.BoxLayout({});
+ const box = new St.BoxLayout({});
this.add_child(box);
- let resultTxt = new St.Label({text: `r(${index}) = `});
+ const resultTxt = new St.Label({text: `r(${index}) = `});
resultTxt.clutter_text.ellipsize = Pango.EllipsizeMode.END;
box.add_child(resultTxt);
- let objLink = new ObjLink(this._lookingGlass, o);
+ const objLink = new ObjLink(this._lookingGlass, o);
box.add_child(objLink);
}
});
name: 'LookingGlassWindows',
orientation: Clutter.Orientation.VERTICAL,
});
- let tracker = Shell.WindowTracker.get_default();
+ const tracker = Shell.WindowTracker.get_default();
this._updateId = Main.initializeDeferredWork(this, this._updateWindowList.bind(this));
global.display.connect('window-created', this._updateWindowList.bind(this));
tracker.connect('tracked-windows-changed', this._updateWindowList.bind(this));
return;
this.destroy_all_children();
- let windows = global.get_window_actors();
- let tracker = Shell.WindowTracker.get_default();
+ const windows = global.get_window_actors();
+ const tracker = Shell.WindowTracker.get_default();
for (let i = 0; i < windows.length; i++) {
- let metaWindow = windows[i].metaWindow;
+ const metaWindow = windows[i].metaWindow;
// Avoid multiple connections
if (!metaWindow._lookingGlassManaged) {
metaWindow.connect('unmanaged', this._updateWindowList.bind(this));
});
box.add_child(header);
- let windowLink = new ObjLink(this._lookingGlass, metaWindow, metaWindow.title);
+ const windowLink = new ObjLink(this._lookingGlass, metaWindow, metaWindow.title);
header.add_child(windowLink);
const propsBox = new St.BoxLayout({
});
box.add_child(propsBox);
propsBox.add_child(new St.Label({text: `wmclass: ${metaWindow.get_wm_class()}`}));
- let app = tracker.get_window_app(metaWindow);
+ const app = tracker.get_window_app(metaWindow);
if (app != null && !app.is_window_backed()) {
- let icon = app.create_icon_texture(22);
- let propBox = new St.BoxLayout({style_class: 'lg-window-props'});
+ const icon = app.create_icon_texture(22);
+ const propBox = new St.BoxLayout({style_class: 'lg-window-props'});
propsBox.add_child(propBox);
propBox.add_child(new St.Label({text: 'app: '}));
- let appLink = new ObjLink(this._lookingGlass, app, app.get_id());
+ const appLink = new ObjLink(this._lookingGlass, app, app.get_id());
propBox.add_child(appLink);
propBox.add_child(icon);
} else {
this._container.destroy_all_children();
- let hbox = new St.BoxLayout({style_class: 'lg-obj-inspector-title'});
+ const hbox = new St.BoxLayout({style_class: 'lg-obj-inspector-title'});
this._container.add_child(hbox);
- let label = new St.Label({
+ const label = new St.Label({
text: `Inspecting: ${typeof obj}: ${objectToString(obj)}`,
x_expand: true,
});
button.connect('clicked', this.close.bind(this));
hbox.add_child(button);
if (typeof obj === typeof {}) {
- let properties = [];
- for (let propName in obj)
+ const properties = [];
+ for (const propName in obj)
properties.push(propName);
properties.sort();
for (let i = 0; i < properties.length; i++) {
- let propName = properties[i];
+ const propName = properties[i];
let link;
try {
- let prop = obj[propName];
+ const prop = obj[propName];
link = new ObjLink(this._lookingGlass, prop);
} catch {
link = new St.Label({text: '<error>'});
}
- let box = new St.BoxLayout();
+ const box = new St.BoxLayout();
box.add_child(new St.Label({text: `${propName}: `}));
box.add_child(link);
this._container.add_child(box);
}
_onInsert() {
- let obj = this._obj;
+ const obj = this._obj;
this.close();
this._lookingGlass.insertObject(obj);
}
}
vfunc_paint_node(node, paintContext) {
- let actor = this.get_actor();
+ const actor = this.get_actor();
const actorNode = new Clutter.ActorNode(actor, -1);
node.add_child(actorNode);
const framebuffer = paintContext.get_framebuffer();
const coglContext = framebuffer.get_context();
- let color = new Cogl.Color();
+ const color = new Cogl.Color();
color.init_from_4f(1.0, 0.0, 0.0, 196.0 / 255.0);
this._pipeline = Cogl.Pipeline.new(coglContext);
this._pipeline.set_color(color);
}
- let alloc = actor.get_allocation_box();
- let width = 2;
+ const alloc = actor.get_allocation_box();
+ const width = 2;
const pipelineNode = new Clutter.PipelineNode(this._pipeline);
pipelineNode.set_name('Red Border');
if (!this._eventHandler)
return;
- let primary = Main.layoutManager.primaryMonitor;
+ const primary = Main.layoutManager.primaryMonitor;
- let [, , natWidth, natHeight] =
+ const [, , natWidth, natHeight] =
this._eventHandler.get_preferred_size();
- let childBox = new Clutter.ActorBox();
+ const childBox = new Clutter.ActorBox();
childBox.x1 = primary.x + Math.floor((primary.width - natWidth) / 2);
childBox.x2 = childBox.x1 + natWidth;
childBox.y1 = primary.y + Math.floor((primary.height - natHeight) / 2);
_onButtonPressEvent(actor, event) {
if (this._target) {
- let [stageX, stageY] = event.get_coords();
+ const [stageX, stageY] = event.get_coords();
this.emit('target', this._target, stageX, stageY);
}
this._close();
switch (event.get_scroll_direction()) {
case Clutter.ScrollDirection.UP: {
// select parent
- let parent = this._target.get_parent();
+ const parent = this._target.get_parent();
if (parent != null) {
this._target = parent;
this._update(event);
if (this._target !== this._pointerTarget) {
let child = this._pointerTarget;
while (child) {
- let parent = child.get_parent();
+ const parent = child.get_parent();
if (parent === this._target)
break;
child = parent;
}
_update(event) {
- let [stageX, stageY] = event.get_coords();
- let target = global.stage.get_actor_at_pos(
+ const [stageX, stageY] = event.get_coords();
+ const target = global.stage.get_actor_at_pos(
Clutter.PickMode.ALL, stageX, stageY);
if (target !== this._pointerTarget)
this._target = target;
this._pointerTarget = target;
- let position = `[inspect x: ${stageX} y: ${stageY}]`;
+ const position = `[inspect x: ${stageX} y: ${stageY}]`;
this._displayText.text = '';
this._displayText.text = `${position} ${this._target}`;
}
_loadExtension(o, uuid) {
- let extension = Main.extensionManager.lookup(uuid);
+ const extension = Main.extensionManager.lookup(uuid);
// There can be cases where we create dummy extension metadata
// that's not really a proper extension. Don't bother with these.
if (!extension.metadata.name)
return;
- let extensionDisplay = this._createExtensionDisplay(extension);
+ const extensionDisplay = this._createExtensionDisplay(extension);
if (this._numExtensions === 0)
this._extensionsList.remove_child(this._noExtensions);
}
_onViewSource(actor) {
- let extension = actor._extension;
- let uri = extension.dir.get_uri();
+ const extension = actor._extension;
+ const uri = extension.dir.get_uri();
Gio.app_info_launch_default_for_uri(uri, global.create_app_launch_context(0, -1));
this._lookingGlass.close();
}
_onWebPage(actor) {
- let extension = actor._extension;
+ const extension = actor._extension;
Gio.app_info_launch_default_for_uri(extension.metadata.url, global.create_app_launch_context(0, -1));
this._lookingGlass.close();
}
_onViewErrors(actor) {
- let extension = actor._extension;
- let shouldShow = !actor._isShowing;
+ const extension = actor._extension;
+ const shouldShow = !actor._isShowing;
if (shouldShow) {
- let errors = extension.errors;
+ const errors = extension.errors;
const errorDisplay = new St.BoxLayout({
orientation: Clutter.Orientation.VERTICAL,
});
errorDisplay.add_child(new St.Label({text: errors[i]}));
} else {
/* Translators: argument is an extension UUID. */
- let message = _('%s has not emitted any errors').format(extension.uuid);
+ const message = _('%s has not emitted any errors').format(extension.uuid);
errorDisplay.add_child(new St.Label({text: message}));
}
orientation: Clutter.Orientation.VERTICAL,
});
box._extension = extension;
- let name = new St.Label({
+ const name = new St.Label({
style_class: 'lg-extension-name',
text: extension.metadata.name,
x_expand: true,
});
box.add_child(name);
- let description = new St.Label({
+ const description = new St.Label({
style_class: 'lg-extension-description',
text: extension.metadata.description || 'No description',
x_expand: true,
});
box.add_child(description);
- let metaBox = new St.BoxLayout({style_class: 'lg-extension-meta'});
+ const metaBox = new St.BoxLayout({style_class: 'lg-extension-meta'});
box.add_child(metaBox);
const state = new St.Label({
style_class: 'lg-extension-state',
this._removeActor(child);
});
- for (let child of actor)
+ for (const child of actor)
this._addActor(data.children, child);
}
if (!data || !data.visible)
return;
- for (let child of actor)
+ for (const child of actor)
this._removeActor(child);
data.visible = false;
if (!data)
return;
- for (let child of actor)
+ for (const child of actor)
this._removeActor(child);
if (data.actorAddedId > 0) {
Main.uiGroup.add_child(this._objInspector);
this._objInspector.hide();
- let toolbar = new St.BoxLayout({name: 'Toolbar'});
+ const toolbar = new St.BoxLayout({name: 'Toolbar'});
this.add_child(toolbar);
const inspectButton = new St.Button({
style_class: 'lg-toolbar-button',
});
toolbar.add_child(inspectButton);
inspectButton.connect('clicked', () => {
- let inspector = new Inspector(this);
+ const inspector = new Inspector(this);
inspector.connect('target', (i, target, stageX, stageY) => {
this._pushResult(`inspect(${Math.round(stageX)}, ${Math.round(stageY)})`, target);
});
return Clutter.EVENT_PROPAGATE;
});
- let notebook = new Notebook();
+ const notebook = new Notebook();
this._notebook = notebook;
this.add_child(notebook);
- let emptyBox = new St.Bin({x_expand: true});
+ const emptyBox = new St.Bin({x_expand: true});
toolbar.add_child(emptyBox);
toolbar.add_child(notebook.tabControls);
});
this._evalBox.add_child(this._entryArea);
- let label = new St.Label({text: CHEVRON});
+ const label = new St.Label({text: CHEVRON});
this._entryArea.add_child(label);
this._entry = new St.Entry({
}
_pushResult(command, obj) {
- let index = this._resultsArea.get_n_children() + this._offset;
- let result = new Result(this, CHEVRON + command, obj, index);
+ const index = this._resultsArea.get_n_children() + this._offset;
+ const result = new Result(this, CHEVRON + command, obj, index);
this._resultsArea.add_child(result);
if (obj instanceof Clutter.Actor)
this.setBorderPaintTarget(obj);
// Setting the height to -1 allows us to get its actual preferred height rather than
// whatever was last set when animating
this._completionActor.set_height(-1);
- let [, naturalHeight] = this._completionActor.get_preferred_height(this._resultsArea.get_width());
+ const [, naturalHeight] = this._completionActor.get_preferred_height(this._resultsArea.get_width());
// Don't reanimate if we are already visible
if (this._completionActor.visible) {
this._completionActor.height = naturalHeight;
} else {
- let settings = St.Settings.get();
- let duration = AUTO_COMPLETE_SHOW_COMPLETION_ANIMATION_DURATION / settings.slow_down_factor;
+ const settings = St.Settings.get();
+ const duration = AUTO_COMPLETE_SHOW_COMPLETION_ANIMATION_DURATION / settings.slow_down_factor;
this._completionActor.show();
this._completionActor.remove_all_transitions();
this._completionActor.ease({
_hideCompletions() {
if (this._completionActor) {
- let settings = St.Settings.get();
- let duration = AUTO_COMPLETE_SHOW_COMPLETION_ANIMATION_DURATION / settings.slow_down_factor;
+ const settings = St.Settings.get();
+ const duration = AUTO_COMPLETE_SHOW_COMPLETION_ANIMATION_DURATION / settings.slow_down_factor;
this._completionActor.remove_all_transitions();
this._completionActor.ease({
height: 0,
if (!command)
return;
- let lines = command.split(';');
+ const lines = command.split(';');
lines.push(`return ${lines.pop()}`);
- let fullCmd = commandHeader + lines.join(';');
+ const fullCmd = commandHeader + lines.join(';');
let resultObj;
try {
}
_resize() {
- let primary = Main.layoutManager.primaryMonitor;
- let myWidth = primary.width * 0.7;
- let availableHeight = primary.height - Main.layoutManager.keyboardBox.height;
- let myHeight = Math.min(primary.height * 0.7, availableHeight * 0.9);
+ const primary = Main.layoutManager.primaryMonitor;
+ const myWidth = primary.width * 0.7;
+ const availableHeight = primary.height - Main.layoutManager.keyboardBox.height;
+ const myHeight = Math.min(primary.height * 0.7, availableHeight * 0.9);
this.x = primary.x + (primary.width - myWidth) / 2;
this._hiddenY = primary.y + Main.layoutManager.panelBox.height - myHeight;
this._targetY = this._hiddenY + myHeight;
// Handle key events which are relevant for all tabs of the LookingGlass
vfunc_key_press_event(event) {
- let symbol = event.get_key_symbol();
+ const symbol = event.get_key_symbol();
if (symbol === Clutter.KEY_Escape) {
this.close();
return Clutter.EVENT_STOP;
if (this._open)
return;
- let grab = Main.pushModal(this, {actionMode: Shell.ActionMode.LOOKING_GLASS});
+ const grab = Main.pushModal(this, {actionMode: Shell.ActionMode.LOOKING_GLASS});
if (grab.get_seat_state() !== Clutter.GrabState.ALL) {
Main.popModal(grab);
return;
// We inverse compensate for the slow-down so you can change the factor
// through LookingGlass without long waits.
- let duration = LG_ANIMATION_TIME / St.Settings.get().slow_down_factor;
+ const duration = LG_ANIMATION_TIME / St.Settings.get().slow_down_factor;
this.ease({
y: this._targetY,
duration,
this.setBorderPaintTarget(null);
- let settings = St.Settings.get();
- let duration = Math.min(
+ const settings = St.Settings.get();
+ const duration = Math.min(
LG_ANIMATION_TIME / settings.slow_down_factor,
LG_ANIMATION_TIME);
this.ease({
if (!this._texture)
return [false, 0, 0];
- let width = this._texture.get_width() / this._scale;
- let height = this._texture.get_height() / this._scale;
+ const width = this._texture.get_width() / this._scale;
+ const height = this._texture.get_height() / this._scale;
return [true, width, height];
}
if (!this._texture)
return;
- let [minFilter, magFilter] = actor.get_content_scaling_filters();
- let textureNode = new Clutter.TextureNode(this._texture,
+ const [minFilter, magFilter] = actor.get_content_scaling_filters();
+ const textureNode = new Clutter.TextureNode(this._texture,
null, minFilter, magFilter);
textureNode.set_name('MouseSpriteContent');
node.add_child(textureNode);
* and so we should actually add an API to mutter that will allow us
* to know the real sprite texture scaling in order to adapt it to the
* wanted one. */
- let avgSize = (this._texture.get_width() + this._texture.get_height()) / 2;
+ const avgSize = (this._texture.get_width() + this._texture.get_height()) / 2;
return Math.max(1, Math.floor(avgSize / Meta.prefs_get_cursor_size() + .1));
}
_recomputeScale() {
- let scale = this._textureScale() / this._monitorScale;
+ const scale = this._textureScale() / this._monitorScale;
if (this._scale !== scale) {
this._scale = scale;
if (this._texture === coglTexture)
return;
- let oldTexture = this._texture;
+ const oldTexture = this._texture;
this._texture = coglTexture;
this.invalidate();
[this.xMouse, this.yMouse] = global.get_pointer();
- let aZoomRegion = new ZoomRegion(this, this._cursorRoot);
+ const aZoomRegion = new ZoomRegion(this, this._cursorRoot);
this._zoomRegions.push(aZoomRegion);
this._settingsInit(aZoomRegion);
aZoomRegion.scrollContentsTo(this.xMouse, this.yMouse);
}
_updateContentScale() {
- let monitor = Main.layoutManager.findMonitorForPoint(this.xMouse,
+ const monitor = Main.layoutManager.findMonitorForPoint(this.xMouse,
this.yMouse);
this._mouseSprite.content.monitorScale = monitor
? monitor.geometry_scale : 1;
* @param {boolean} activate Boolean to activate or de-activate the magnifier.
*/
setActive(activate) {
- let isActive = this.isActive();
+ const isActive = this.isActive();
this._zoomRegions.forEach(zoomRegion => {
zoomRegion.setActive(activate);
*/
startTrackingMouse() {
if (!this._pointerWatch) {
- let interval = 1000 / 60;
+ const interval = 1000 / 60;
this._pointerWatch = PointerWatcher.getPointerWatcher().addWatch(interval, this.scrollToMousePos.bind(this));
this.scrollToMousePos();
* @returns {ZoomRegion} the newly created ZoomRegion.
*/
createZoomRegion(xMagFactor, yMagFactor, roi, viewPort) {
- let zoomRegion = new ZoomRegion(this, this._cursorRoot);
+ const zoomRegion = new ZoomRegion(this, this._cursorRoot);
zoomRegion.setViewPort(viewPort);
// We ignore the redundant width/height on the ROI
- let fixedROI = Object.create(roi);
+ const fixedROI = Object.create(roi);
fixedROI.width = viewPort.width / xMagFactor;
fixedROI.height = viewPort.height / yMagFactor;
zoomRegion.setROI(fixedROI);
if (!this._crossHairs)
this._crossHairs = new Crosshairs();
- let thickness = this._settings.get_int(CROSS_HAIRS_THICKNESS_KEY);
- let color = this._settings.get_string(CROSS_HAIRS_COLOR_KEY);
- let opacity = this._settings.get_double(CROSS_HAIRS_OPACITY_KEY);
- let length = this._settings.get_int(CROSS_HAIRS_LENGTH_KEY);
- let clip = this._settings.get_boolean(CROSS_HAIRS_CLIP_KEY);
+ const thickness = this._settings.get_int(CROSS_HAIRS_THICKNESS_KEY);
+ const color = this._settings.get_string(CROSS_HAIRS_COLOR_KEY);
+ const opacity = this._settings.get_double(CROSS_HAIRS_OPACITY_KEY);
+ const length = this._settings.get_int(CROSS_HAIRS_LENGTH_KEY);
+ const clip = this._settings.get_boolean(CROSS_HAIRS_CLIP_KEY);
this.setCrosshairsThickness(thickness);
this.setCrosshairsColor(color);
this.setCrosshairsLength(length);
this.setCrosshairsClip(clip);
- let theCrossHairs = this._crossHairs;
+ const theCrossHairs = this._crossHairs;
this._zoomRegions.forEach(zoomRegion => {
zoomRegion.addCrosshairs(theCrossHairs);
});
*/
setCrosshairsColor(color) {
if (this._crossHairs) {
- let [res_, clutterColor] = Cogl.Color.from_string(color);
+ const [res_, clutterColor] = Cogl.Color.from_string(color);
this._crossHairs.setColor(clutterColor);
}
}
*/
setCrosshairsLength(length) {
if (this._crossHairs) {
- let scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
+ const scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
this._crossHairs.setLength(length / scaleFactor);
}
}
*/
getCrosshairsClip() {
if (this._crossHairs) {
- let [clipWidth, clipHeight] = this._crossHairs.getClip();
+ const [clipWidth, clipHeight] = this._crossHairs.getClip();
return clipWidth > 0 && clipHeight > 0;
} else {
return false;
_updateMouseSprite() {
this._updateSpriteTexture();
- let [xHot, yHot] = this._cursorTracker.get_hot();
+ const [xHot, yHot] = this._cursorTracker.get_hot();
this._mouseSprite.set({
translation_x: -xHot,
translation_y: -yHot,
}
_updateSpriteTexture() {
- let sprite = this._cursorTracker.get_sprite();
+ const sprite = this._cursorTracker.get_sprite();
if (sprite) {
this._mouseSprite.content.texture = sprite;
if (aPref)
zoomRegion.setColorSaturation(aPref);
- let bc = {};
+ const bc = {};
bc.r = this._settings.get_double(BRIGHT_RED_KEY);
bc.g = this._settings.get_double(BRIGHT_GREEN_KEY);
bc.b = this._settings.get_double(BRIGHT_BLUE_KEY);
zoomRegion.setContrast(bc);
}
- let showCrosshairs = this._settings.get_boolean(SHOW_CROSS_HAIRS_KEY);
+ const showCrosshairs = this._settings.get_boolean(SHOW_CROSS_HAIRS_KEY);
this.addCrosshairs();
this.setCrosshairsVisible(showCrosshairs);
}
_updateScreenPosition() {
// Applies only to the first zoom region.
if (this._zoomRegions.length) {
- let position = this._settings.get_enum(SCREEN_POSITION_KEY);
+ const position = this._settings.get_enum(SCREEN_POSITION_KEY);
this._zoomRegions[0].setScreenPosition(position);
if (position !== GDesktopEnums.MagnifierScreenPosition.FULL_SCREEN)
this._updateLensMode();
// Applies only to the first zoom region.
if (this._zoomRegions.length) {
// Mag factor is accurate to two decimal places.
- let magFactor = parseFloat(this._settings.get_double(MAG_FACTOR_KEY).toFixed(2));
+ const magFactor = parseFloat(this._settings.get_double(MAG_FACTOR_KEY).toFixed(2));
this._zoomRegions[0].setMagFactor(magFactor, magFactor);
}
}
_updateBrightness() {
// Applies only to the first zoom region.
if (this._zoomRegions.length) {
- let brightness = {};
+ const brightness = {};
brightness.r = this._settings.get_double(BRIGHT_RED_KEY);
brightness.g = this._settings.get_double(BRIGHT_GREEN_KEY);
brightness.b = this._settings.get_double(BRIGHT_BLUE_KEY);
_updateContrast() {
// Applies only to the first zoom region.
if (this._zoomRegions.length) {
- let contrast = {};
+ const contrast = {};
contrast.r = this._settings.get_double(CONTRAST_RED_KEY);
contrast.g = this._settings.get_double(CONTRAST_GREEN_KEY);
contrast.b = this._settings.get_double(CONTRAST_BLUE_KEY);
}
_disconnectSignals() {
- for (let [obj, id] of this._signalConnections)
+ for (const [obj, id] of this._signalConnections)
obj.disconnect(id);
delete this._signalConnections;
}
_updateFocus(caller, event) {
- let component = event.source.get_component_iface();
+ const component = event.source.get_component_iface();
if (!component || event.detail1 !== 1)
return;
let extents;
}
_updateCaret(caller, event) {
- let text = event.source.get_text_iface();
+ const text = event.source.get_text_iface();
if (!text)
return;
let extents;
}
_syncFocusTracking() {
- let enabled = this._focusTrackingMode !== GDesktopEnums.MagnifierFocusTrackingMode.NONE &&
+ const enabled = this._focusTrackingMode !== GDesktopEnums.MagnifierFocusTrackingMode.NONE &&
this.isActive();
if (enabled)
}
_syncCaretTracking() {
- let enabled = this._caretTrackingMode !== GDesktopEnums.MagnifierCaretTrackingMode.NONE &&
+ const enabled = this._caretTrackingMode !== GDesktopEnums.MagnifierCaretTrackingMode.NONE &&
this.isActive();
if (enabled)
* the bounding rectangle of what is shown in the magnified view.
*/
getROI() {
- let roiWidth = this._viewPortWidth / this._xMagFactor;
- let roiHeight = this._viewPortHeight / this._yMagFactor;
+ const roiWidth = this._viewPortWidth / this._xMagFactor;
+ const roiHeight = this._viewPortHeight / this._yMagFactor;
return [
this._xCenter - roiWidth / 2,
* Magnifier view occupies the top half of the screen.
*/
setTopHalf() {
- let viewPort = {};
+ const viewPort = {};
viewPort.x = 0;
viewPort.y = 0;
viewPort.width = global.screen_width;
* Magnifier view occupies the bottom half of the screen.
*/
setBottomHalf() {
- let viewPort = {};
+ const viewPort = {};
viewPort.x = 0;
viewPort.y = global.screen_height / 2;
viewPort.width = global.screen_width;
* Magnifier view occupies the left half of the screen.
*/
setLeftHalf() {
- let viewPort = {};
+ const viewPort = {};
viewPort.x = 0;
viewPort.y = 0;
viewPort.width = global.screen_width / 2;
* Magnifier view occupies the right half of the screen.
*/
setRightHalf() {
- let viewPort = {};
+ const viewPort = {};
viewPort.x = global.screen_width / 2;
viewPort.y = 0;
viewPort.width = global.screen_width / 2;
* Note: disallows lens mode.
*/
setFullScreenMode() {
- let viewPort = {};
+ const viewPort = {};
viewPort.x = 0;
viewPort.y = 0;
viewPort.width = global.screen_width;
* the contrast for the red, green, and blue channels.
*/
getContrast() {
- let contrast = {};
+ const contrast = {};
contrast.r = this._contrast.r;
contrast.g = this._contrast.g;
contrast.b = this._contrast.b;
_setViewPort(viewPort, fromROIUpdate) {
// Sets the position of the zoom region on the screen
- let width = Math.round(Math.min(viewPort.width, global.screen_width));
- let height = Math.round(Math.min(viewPort.height, global.screen_height));
+ const width = Math.round(Math.min(viewPort.width, global.screen_width));
+ const height = Math.round(Math.min(viewPort.height, global.screen_height));
let x = Math.max(viewPort.x, 0);
let y = Math.max(viewPort.y, 0);
}
if (this._clampScrollingAtEdges) {
- let roiWidth = this._viewPortWidth / this._xMagFactor;
- let roiHeight = this._viewPortHeight / this._yMagFactor;
+ const roiWidth = this._viewPortWidth / this._xMagFactor;
+ const roiHeight = this._viewPortHeight / this._yMagFactor;
params.xCenter = Math.min(params.xCenter, global.screen_width - roiWidth / 2);
params.xCenter = Math.max(params.xCenter, roiWidth / 2);
// mouse's position is not given, then it is fetched.
let mouseIsOver = false;
if (this.isActive()) {
- let xMouse = this._magnifier.xMouse;
- let yMouse = this._magnifier.yMouse;
+ const xMouse = this._magnifier.xMouse;
+ const yMouse = this._magnifier.yMouse;
mouseIsOver =
xMouse >= this._viewPortX && xMouse < (this._viewPortX + this._viewPortWidth) &&
// Determines where the center should be given the current cursor
// position and mouse tracking mode
- let xMouse = this._magnifier.xMouse;
- let yMouse = this._magnifier.yMouse;
+ const xMouse = this._magnifier.xMouse;
+ const yMouse = this._magnifier.yMouse;
if (this._mouseTrackingMode === GDesktopEnums.MagnifierMouseTrackingMode.PROPORTIONAL)
return this._centerFromPointProportional(xMouse, yMouse);
}
_centerFromPointPush(xPoint, yPoint) {
- let [xRoi, yRoi, widthRoi, heightRoi] = this.getROI();
- let [cursorWidth, cursorHeight] = this._mouseSourceActor.get_size();
+ const [xRoi, yRoi, widthRoi, heightRoi] = this.getROI();
+ const [cursorWidth, cursorHeight] = this._mouseSourceActor.get_size();
let xPos = xRoi + widthRoi / 2;
let yPos = yRoi + heightRoi / 2;
- let xRoiRight = xRoi + widthRoi - cursorWidth;
- let yRoiBottom = yRoi + heightRoi - cursorHeight;
+ const xRoiRight = xRoi + widthRoi - cursorWidth;
+ const yRoiBottom = yRoi + heightRoi - cursorHeight;
if (xPoint < xRoi)
xPos -= xRoi - xPoint;
}
_centerFromPointProportional(xPoint, yPoint) {
- let [xRoi_, yRoi_, widthRoi, heightRoi] = this.getROI();
- let halfScreenWidth = global.screen_width / 2;
- let halfScreenHeight = global.screen_height / 2;
+ const [xRoi_, yRoi_, widthRoi, heightRoi] = this.getROI();
+ const halfScreenWidth = global.screen_width / 2;
+ const halfScreenHeight = global.screen_height / 2;
// We want to pad with a constant distance after zooming, so divide
// by the magnification factor.
- let unscaledPadding = Math.min(this._viewPortWidth, this._viewPortHeight) / 5;
- let xPadding = unscaledPadding / this._xMagFactor;
- let yPadding = unscaledPadding / this._yMagFactor;
- let xProportion = (xPoint - halfScreenWidth) / halfScreenWidth; // -1 ... 1
- let yProportion = (yPoint - halfScreenHeight) / halfScreenHeight; // -1 ... 1
- let xPos = xPoint - xProportion * (widthRoi / 2 - xPadding);
- let yPos = yPoint - yProportion * (heightRoi / 2 - yPadding);
+ const unscaledPadding = Math.min(this._viewPortWidth, this._viewPortHeight) / 5;
+ const xPadding = unscaledPadding / this._xMagFactor;
+ const yPadding = unscaledPadding / this._yMagFactor;
+ const xProportion = (xPoint - halfScreenWidth) / halfScreenWidth; // -1 ... 1
+ const yProportion = (yPoint - halfScreenHeight) / halfScreenHeight; // -1 ... 1
+ const xPos = xPoint - xProportion * (widthRoi / 2 - xPadding);
+ const yPos = yPoint - yProportion * (heightRoi / 2 - yPadding);
return [xPos, yPos];
}
if (!this.isActive())
return;
- let [x, y] = this._screenToViewPort(0, 0);
+ const [x, y] = this._screenToViewPort(0, 0);
this._uiGroupClone.ease({
x: Math.round(x),
y: Math.round(y),
duration: animate ? 100 : 0,
});
- let [mouseX, mouseY] = this._getMousePosition();
+ const [mouseX, mouseY] = this._getMousePosition();
this._mouseActor.ease({
x: mouseX,
y: mouseY,
});
if (this._crossHairsActor) {
- let [crossX, crossY] = this._getCrossHairsPosition();
+ const [crossX, crossY] = this._getCrossHairsPosition();
this._crossHairsActor.ease({
x: crossX,
y: crossY,
}
_updateMousePosition() {
- let [xMagMouse, yMagMouse] = this._getMousePosition();
+ const [xMagMouse, yMagMouse] = this._getMousePosition();
this._mouseActor.set_position(xMagMouse, yMagMouse);
if (this._crossHairsActor) {
- let [crossX, crossY] = this._getCrossHairsPosition();
+ const [crossX, crossY] = this._getCrossHairsPosition();
this._crossHairsActor.set_position(crossX, crossY);
}
}
_getMousePosition() {
- let [xMagMouse, yMagMouse] = this._screenToViewPort(
+ const [xMagMouse, yMagMouse] = this._screenToViewPort(
this._magnifier.xMouse, this._magnifier.yMouse);
return [Math.round(xMagMouse), Math.round(yMagMouse)];
}
_getCrossHairsPosition() {
- let [xMagMouse, yMagMouse] = this._getMousePosition();
- let [groupWidth, groupHeight] = this._crossHairsActor.get_size();
+ const [xMagMouse, yMagMouse] = this._getMousePosition();
+ const [groupWidth, groupHeight] = this._crossHairsActor.get_size();
return [xMagMouse - groupWidth / 2, yMagMouse - groupHeight / 2];
}
// Set the group containing the crosshairs to three times the desktop
// size in case the crosshairs need to appear to be infinite in
// length (i.e., extend beyond the edges of the view they appear in).
- let groupWidth = global.screen_width * 3;
- let groupHeight = global.screen_height * 3;
+ const groupWidth = global.screen_width * 3;
+ const groupHeight = global.screen_height * 3;
super._init({
clip_to_allocation: false,
addToZoomRegion(zoomRegion, magnifiedMouse) {
let crosshairsActor = null;
if (zoomRegion && magnifiedMouse) {
- let container = magnifiedMouse.get_parent();
+ const container = magnifiedMouse.get_parent();
if (container) {
crosshairsActor = this;
if (this.get_parent() != null) {
container.add_child(crosshairsActor);
container.set_child_above_sibling(magnifiedMouse, crosshairsActor);
- let [xMouse, yMouse] = magnifiedMouse.get_position();
- let [crosshairsWidth, crosshairsHeight] = crosshairsActor.get_size();
+ const [xMouse, yMouse] = magnifiedMouse.get_position();
+ const [crosshairsWidth, crosshairsHeight] = crosshairsActor.get_size();
crosshairsActor.set_position(xMouse - crosshairsWidth / 2, yMouse - crosshairsHeight / 2);
}
}
* @param {[number, number]} [clipSize] If present, the clip's [width, height].
*/
reCenter(clipSize) {
- let [groupWidth, groupHeight] = this.get_size();
- let leftLength = this._horizLeftHair.get_width();
- let topLength = this._vertTopHair.get_height();
- let thickness = this._horizLeftHair.get_height();
+ const [groupWidth, groupHeight] = this.get_size();
+ const leftLength = this._horizLeftHair.get_width();
+ const topLength = this._vertTopHair.get_height();
+ const thickness = this._horizLeftHair.get_height();
// Deal with clip rectangle.
if (clipSize)
this._clipSize = clipSize;
- let clipWidth = this._clipSize[0];
- let clipHeight = this._clipSize[1];
+ const clipWidth = this._clipSize[0];
+ const clipHeight = this._clipSize[1];
- let left = groupWidth / 2 - clipWidth / 2 - leftLength - thickness / 2;
- let right = groupWidth / 2 + clipWidth / 2 + thickness / 2;
- let top = groupHeight / 2 - clipHeight / 2 - topLength - thickness / 2;
- let bottom = groupHeight / 2 + clipHeight / 2 + thickness / 2;
+ const left = groupWidth / 2 - clipWidth / 2 - leftLength - thickness / 2;
+ const right = groupWidth / 2 + clipWidth / 2 + thickness / 2;
+ const top = groupHeight / 2 - clipHeight / 2 - topLength - thickness / 2;
+ const bottom = groupHeight / 2 + clipHeight / 2 + thickness / 2;
this._horizLeftHair.set_position(left, (groupHeight - thickness) / 2);
this._horizRightHair.set_position(right, (groupHeight - thickness) / 2);
this._vertTopHair.set_position((groupWidth - thickness) / 2, top);
* {number} brightness.b - the blue component
*/
setBrightness(brightness) {
- let bRed = brightness.r;
- let bGreen = brightness.g;
- let bBlue = brightness.b;
+ const bRed = brightness.r;
+ const bGreen = brightness.g;
+ const bBlue = brightness.b;
this._brightnessContrast.set_brightness_full(bRed, bGreen, bBlue);
// Enable the effect if the brightness OR contrast change are such that
// it modifies the brightness and/or contrast.
- let [cRed, cGreen, cBlue] = this._brightnessContrast.get_contrast();
+ const [cRed, cGreen, cBlue] = this._brightnessContrast.get_contrast();
this._brightnessContrast.set_enabled(
bRed !== NO_CHANGE || bGreen !== NO_CHANGE || bBlue !== NO_CHANGE ||
cRed !== NO_CHANGE || cGreen !== NO_CHANGE || cBlue !== NO_CHANGE);
* {number} contrast.b - the blue component
*/
setContrast(contrast) {
- let cRed = contrast.r;
- let cGreen = contrast.g;
- let cBlue = contrast.b;
+ const cRed = contrast.r;
+ const cGreen = contrast.g;
+ const cBlue = contrast.b;
this._brightnessContrast.set_contrast_full(cRed, cGreen, cBlue);
// it modifies the brightness and/or contrast.
// should be able to use Cogl.Color.equal(), but that complains of
// a null first argument.
- let [bRed, bGreen, bBlue] = this._brightnessContrast.get_brightness();
+ const [bRed, bGreen, bBlue] = this._brightnessContrast.get_brightness();
this._brightnessContrast.set_enabled(
cRed !== NO_CHANGE || cGreen !== NO_CHANGE || cBlue !== NO_CHANGE ||
bRed !== NO_CHANGE || bGreen !== NO_CHANGE || bBlue !== NO_CHANGE);
export let shellAudioSelectionDBusService = null;
export let shellDBusService = null;
export let shellMountOpDBusService = null;
-export let screenSaverDBus = null;
+export const screenSaverDBus = null;
export let modalCount = 0;
export let actionMode = Shell.ActionMode.NONE;
-export let modalActorFocusStack = [];
+export const modalActorFocusStack = [];
export let uiGroup = null;
export let magnifier = null;
export let xdndHandler = null;
welcomeDialog.close();
}
- let remoteAccessController = global.backend.get_remote_access_controller();
+ const remoteAccessController = global.backend.get_remote_access_controller();
if (remoteAccessController && !global.backend.is_headless()) {
if (sessionMode.allowScreencast && _remoteAccessInhibited) {
remoteAccessController.uninhibit_remote_access();
notifyError(msg, detail);
});
- let currentDesktop = GLib.getenv('XDG_CURRENT_DESKTOP');
+ const currentDesktop = GLib.getenv('XDG_CURRENT_DESKTOP');
if (!currentDesktop || !currentDesktop.split(':').includes('GNOME'))
GioUnix.DesktopAppInfo.set_desktop_env('GNOME');
}
if (!perfModule) {
- let credentials = new Gio.Credentials();
+ const credentials = new Gio.Credentials();
if (credentials.get_unix_user() === 0) {
notify(
_('Logged in as a privileged user'),
LoginManager.registerSessionWithGDM();
if (perfModule) {
- let perfOutput = GLib.getenv('SHELL_PERF_OUTPUT');
+ const perfOutput = GLib.getenv('SHELL_PERF_OUTPUT');
Scripting.runPerfScript(perfModule, perfOutput);
}
});
if (stylesheet.query_exists(null))
return stylesheet;
- let dataDirs = GLib.get_system_data_dirs();
+ const dataDirs = GLib.get_system_data_dirs();
for (let i = 0; i < dataDirs.length; i++) {
- let path = GLib.build_filenamev([dataDirs[i], 'gnome-shell', 'theme', name]);
+ const path = GLib.build_filenamev([dataDirs[i], 'gnome-shell', 'theme', name]);
stylesheet = Gio.file_new_for_path(path);
if (stylesheet.query_exists(null))
return stylesheet;
function _getDefaultStylesheet() {
let stylesheet = null;
- let name = sessionMode.stylesheetName;
+ const name = sessionMode.stylesheetName;
// Look for a high-contrast variant first
if (St.Settings.get().high_contrast)
}
function _loadDefaultStylesheet() {
- let stylesheet = _getDefaultStylesheet();
+ const stylesheet = _getDefaultStylesheet();
if (_defaultCssStylesheet && _defaultCssStylesheet.equal(stylesheet))
return;
* Reloads the theme CSS file
*/
export function loadTheme() {
- let themeContext = St.ThemeContext.get_for_stage(global.stage);
- let previousTheme = themeContext.get_theme();
+ const themeContext = St.ThemeContext.get_for_stage(global.stage);
+ const previousTheme = themeContext.get_theme();
- let theme = new St.Theme({
+ const theme = new St.Theme({
application_stylesheet: _cssStylesheet,
default_stylesheet: _defaultCssStylesheet,
});
throw new Error(`No valid stylesheet found for '${sessionMode.stylesheetName}'`);
if (previousTheme) {
- let customStylesheets = previousTheme.get_custom_stylesheets();
+ const customStylesheets = previousTheme.get_custom_stylesheets();
for (let i = 0; i < customStylesheets.length; i++)
theme.load_stylesheet(customStylesheets[i]);
...params,
};
- let grab = global.stage.grab(actor);
+ const grab = global.stage.grab(actor);
if (modalCount === 0)
global.compositor.disable_unredirect();
modalCount += 1;
- let actorDestroyId = actor.connect('destroy', () => {
- let index = _findModal(grab);
+ const actorDestroyId = actor.connect('destroy', () => {
+ const index = _findModal(grab);
if (index >= 0)
popModal(grab);
});
- let prevFocus = global.stage.get_key_focus();
+ const prevFocus = global.stage.get_key_focus();
let prevFocusDestroyId;
if (prevFocus != null) {
prevFocusDestroyId = prevFocus.connect('destroy', () => {
* @param {Clutter.Grab} grab - the grab given by pushModal()
*/
export function popModal(grab) {
- let focusIndex = _findModal(grab);
+ const focusIndex = _findModal(grab);
if (focusIndex < 0) {
global.stage.set_key_focus(null);
actionMode = Shell.ActionMode.NORMAL;
modalCount -= 1;
- let record = modalActorFocusStack[focusIndex];
+ const record = modalActorFocusStack[focusIndex];
record.actor.disconnect(record.destroyId);
record.grab.dismiss();
// record, then the focus stack will be [a, c], rather than the correct
// [a, b]. Shift the focus stack up before removing the record to ensure
// that we get the correct result.
- let t = modalActorFocusStack[modalActorFocusStack.length - 1];
+ const t = modalActorFocusStack[modalActorFocusStack.length - 1];
if (t.prevFocus)
t.prevFocus.disconnect(t.prevFocusDestroyId);
// Remove from the middle, shift the focus chain up
* and switching out of the overview if it's currently active
*/
export function activateWindow(window, time, workspaceNum) {
- let workspaceManager = global.workspace_manager;
- let activeWorkspaceNum = workspaceManager.get_active_workspace_index();
- let windowWorkspaceNum = workspaceNum !== undefined ? workspaceNum : window.get_workspace().index();
+ const workspaceManager = global.workspace_manager;
+ const activeWorkspaceNum = workspaceManager.get_active_workspace_index();
+ const windowWorkspaceNum = workspaceNum !== undefined ? workspaceNum : window.get_workspace().index();
if (!time)
time = global.get_current_time();
if (windowWorkspaceNum !== activeWorkspaceNum) {
- let workspace = workspaceManager.get_workspace_by_index(windowWorkspaceNum);
+ const workspace = workspaceManager.get_workspace_by_index(windowWorkspaceNum);
workspace.activate_with_focus(window, time);
} else {
window.activate(time);
// TODO - replace this timeout with some system to guess when the user might
// be e.g. just reading the screen and not likely to interact.
const DEFERRED_TIMEOUT_SECONDS = 20;
-let _deferredWorkData = {};
+const _deferredWorkData = {};
// Work scheduled for some point in the future
-let _deferredWorkQueue = [];
+const _deferredWorkQueue = [];
// Work we need to process before the next redraw
let _beforeRedrawQueue = [];
// Counter to assign work ids
function _runDeferredWork(workId) {
if (!_deferredWorkData[workId])
return;
- let index = _deferredWorkQueue.indexOf(workId);
+ const index = _deferredWorkQueue.indexOf(workId);
if (index < 0)
return;
function _runBeforeRedrawQueue() {
for (let i = 0; i < _beforeRedrawQueue.length; i++) {
- let workId = _beforeRedrawQueue[i];
+ const workId = _beforeRedrawQueue[i];
_runDeferredWork(workId);
}
_beforeRedrawQueue = [];
*/
export function initializeDeferredWork(actor, callback) {
// Turn into a string so we can use as an object property
- let workId = `${++_deferredWorkSequence}`;
+ const workId = `${++_deferredWorkSequence}`;
_deferredWorkData[workId] = {
actor,
callback,
_queueBeforeRedraw(workId);
});
actor.connect('destroy', () => {
- let index = _deferredWorkQueue.indexOf(workId);
+ const index = _deferredWorkQueue.indexOf(workId);
if (index >= 0)
_deferredWorkQueue.splice(index, 1);
delete _deferredWorkData[workId];
* changed.
*/
export function queueDeferredWork(workId) {
- let data = _deferredWorkData[workId];
+ const data = _deferredWorkData[workId];
if (!data) {
- let message = `Invalid work id ${workId}`;
+ const message = `Invalid work id ${workId}`;
logError(new Error(message), message);
return;
}
destroyOnClose: true,
});
- let label = new St.Label({
+ const label = new St.Label({
text: message,
x_align: Clutter.ActorAlign.CENTER,
y_align: Clutter.ActorAlign.CENTER,
});
function showRestartMessage(message) {
- let restartMessage = new RestartMessage(message);
+ const restartMessage = new RestartMessage(message);
restartMessage.open();
}
});
this._linkColor = '#ccccff';
this.connect('style-changed', () => {
- let [hasColor, color] = this.get_theme_node().lookup_color('link-color', false);
+ const [hasColor, color] = this.get_theme_node().lookup_color('link-color', false);
if (hasColor) {
- let linkColor = color.to_string().substring(0, 7);
+ const linkColor = color.to_string().substring(0, 7);
if (linkColor !== this._linkColor) {
this._linkColor = linkColor;
this._highlightUrls();
_highlightUrls() {
// text here contain markup
- let urls = Util.findUrls(this._text);
+ const urls = Util.findUrls(this._text);
let markup = '';
let pos = 0;
for (let i = 0; i < urls.length; i++) {
- let url = urls[i];
- let str = this._text.substring(pos, url.pos);
+ const url = urls[i];
+ const str = this._text.substring(pos, url.pos);
markup += `${str}<span foreground="${this._linkColor}"><u>${url.url}</u></span>`;
pos = url.pos + url.url.length;
}
[, x, y] = this.transform_stage_point(x, y);
let findPos = -1;
for (let i = 0; i < this.clutter_text.text.length; i++) {
- let [, px, py, lineHeight] = this.clutter_text.position_to_coords(i);
+ const [, px, py, lineHeight] = this.clutter_text.position_to_coords(i);
if (py > y || py + lineHeight < y || x < px)
continue;
findPos = i;
this.expanded = false;
this._useBodyMarkup = false;
- let vbox = new St.BoxLayout({
+ const vbox = new St.BoxLayout({
orientation: Clutter.Orientation.VERTICAL,
x_expand: true,
});
}
vfunc_key_press_event(event) {
- let keysym = event.get_key_symbol();
+ const keysym = event.get_key_symbol();
if (keysym === Clutter.KEY_Delete ||
keysym === Clutter.KEY_KP_Delete ||
icon,
});
- let isPlaying = this._player.status === 'Playing';
- let iconName = isPlaying
+ const isPlaying = this._player.status === 'Playing';
+ const iconName = isPlaying
? 'media-playback-pause-symbolic'
: 'media-playback-start-symbolic';
this._playPauseButton.child.icon_name = iconName;
vfunc_allocate(container, box) {
const childWidth = box.x2 - box.x1;
- let fullY2 = box.y2;
+ const fullY2 = box.y2;
if (this._cover.visible)
this._cover.allocate(box);
}
_focusActorChanged() {
- let focusedActor = global.stage.get_key_focus();
+ const focusedActor = global.stage.get_key_focus();
if (!focusedActor || !this._actor.contains(focusedActor))
this._focusUngrabbed();
}
global.stage.set_key_focus(this._prevKeyFocusActor);
this._prevKeyFocusActor = null;
} else {
- let focusedActor = global.stage.get_key_focus();
+ const focusedActor = global.stage.get_key_focus();
if (focusedActor && this._actor.contains(focusedActor))
global.stage.set_key_focus(null);
}
store() {
this._settings.set_string('application-id', `${this.id}.desktop`);
- let apps = this._masterSettings.get_strv('application-children');
+ const apps = this._masterSettings.get_strv('application-children');
if (!apps.includes(this._canonicalId)) {
apps.push(this._canonicalId);
this._masterSettings.set_strv('application-children', apps);
}
_onNotificationDestroy(notification) {
- let index = this.notifications.indexOf(notification);
+ const index = this.notifications.indexOf(notification);
if (index < 0)
throw new Error('Notification was already removed previously');
this._onStatusChanged(status);
});
- let constraint = new Layout.MonitorConstraint({primary: true});
+ const constraint = new Layout.MonitorConstraint({primary: true});
Main.layoutManager.panelBox.bind_property('visible',
constraint, 'work-area',
GObject.BindingFlags.SYNC_CREATE);
}
_onSourceEnableChanged(policy, source) {
- let wasEnabled = this.contains(source);
- let shouldBeEnabled = policy.enable;
+ const wasEnabled = this.contains(source);
+ const shouldBeEnabled = policy.enable;
if (wasEnabled !== shouldBeEnabled) {
if (shouldBeEnabled)
// If the queue is "full", we skip banner mode and just show a small
// indicator in the panel; however do make an exception for CRITICAL
// notifications, as only banner mode allows expansion.
- let bannerCount = this._notification ? 1 : 0;
- let full = this.queueCount + bannerCount >= MAX_NOTIFICATIONS_IN_QUEUE;
+ const bannerCount = this._notification ? 1 : 0;
+ const full = this.queueCount + bannerCount >= MAX_NOTIFICATIONS_IN_QUEUE;
if (!full || notification.urgency === Urgency.CRITICAL) {
this._notificationQueue.push(notification);
this._notificationQueue.sort(
this._resetNotificationLeftTimeout();
if (this._showNotificationMouseX >= 0) {
- let actorAtShowNotificationPosition =
+ const actorAtShowNotificationPosition =
global.stage.get_actor_at_pos(Clutter.PickMode.ALL, this._showNotificationMouseX, this._showNotificationMouseY);
this._showNotificationMouseX = -1;
this._showNotificationMouseY = -1;
// this._onNotificationLeftTimeout() to determine if the mouse has moved far enough during the initial timeout for us
// to consider that the user intended to leave the tray and therefore hide the tray. If the mouse is still
// close to its previous position, we extend the timeout once.
- let [x, y] = global.get_pointer();
+ const [x, y] = global.get_pointer();
this._notificationLeftMouseX = x;
this._notificationLeftMouseY = y;
// We wait just a little before hiding the message tray in case the user quickly moves the mouse back into it.
// We wait for a longer period if the notification popped up where the mouse pointer was already positioned.
// That gives the user more time to mouse away from the notification and mouse back in in order to expand it.
- let timeout = this._useLongerNotificationLeftTimeout ? LONGER_HIDE_TIMEOUT : HIDE_TIMEOUT;
+ const timeout = this._useLongerNotificationLeftTimeout ? LONGER_HIDE_TIMEOUT : HIDE_TIMEOUT;
this._notificationLeftTimeoutId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, timeout, this._onNotificationLeftTimeout.bind(this));
GLib.Source.set_name_by_id(this._notificationLeftTimeoutId, '[gnome-shell] this._onNotificationLeftTimeout');
}
}
_onNotificationLeftTimeout() {
- let [x, y] = global.get_pointer();
+ const [x, y] = global.get_pointer();
// We extend the timeout once if the mouse moved no further than MOUSE_LEFT_ACTOR_THRESHOLD to either side.
if (this._notificationLeftMouseX > -1 &&
y < this._notificationLeftMouseY + MOUSE_LEFT_ACTOR_THRESHOLD &&
// _updateState() figures out what (if anything) needs to be done
// at the present time.
_updateState() {
- let hasMonitor = Main.layoutManager.primaryMonitor != null;
+ const hasMonitor = Main.layoutManager.primaryMonitor != null;
this.visible = !this._bannerBlocked && hasMonitor && this._banner != null;
if (this._bannerBlocked || !hasMonitor)
return;
if (changed)
this.emit('queue-changed');
- let hasNotifications = Main.sessionMode.hasNotifications;
+ const hasNotifications = Main.sessionMode.hasNotifications;
if (this._notificationState === State.HIDDEN) {
- let nextNotification = this._notificationQueue[0] || null;
+ const nextNotification = this._notificationQueue[0] || null;
if (hasNotifications && nextNotification) {
- let limited = this._busy || Main.layoutManager.primaryMonitor.inFullscreen;
- let showNextNotification = !limited || nextNotification.forFeedback || nextNotification.urgency === Urgency.CRITICAL;
+ const limited = this._busy || Main.layoutManager.primaryMonitor.inFullscreen;
+ const showNextNotification = !limited || nextNotification.forFeedback || nextNotification.urgency === Urgency.CRITICAL;
if (showNextNotification)
this._showNotification();
}
} else if (this._notificationState === State.SHOWING ||
this._notificationState === State.SHOWN) {
- let expired = (this._userActiveWhileNotificationShown &&
+ const expired = (this._userActiveWhileNotificationShown &&
this._notificationState === State.SHOWN &&
this._notificationTimeoutId === 0 &&
this._notification.urgency !== Urgency.CRITICAL &&
!this._pointerInNotification) || this._notificationExpired;
- let mustClose = this._notificationRemoved || !hasNotifications || expired;
+ const mustClose = this._notificationRemoved || !hasNotifications || expired;
if (mustClose) {
- let animate = hasNotifications && !this._notificationRemoved;
+ const animate = hasNotifications && !this._notificationRemoved;
this._hideNotification(animate);
} else if (this._notificationState === State.SHOWN &&
this._pointerInNotification) {
global.compositor.disable_unredirect();
this._updateShowingNotification();
- let [x, y] = global.get_pointer();
+ const [x, y] = global.get_pointer();
// We save the position of the mouse at the time when we started showing the notification
// in order to determine if the notification popped up under it. We make that check if
// the user starts moving the mouse and _onNotificationHoverChanged() gets called. We don't
}
_notificationTimeout() {
- let [x, y] = global.get_pointer();
+ const [x, y] = global.get_pointer();
if (y < this._lastSeenMouseY - 10 && !this._notificationHovered) {
// The mouse is moving towards the notification, so don't
// hide it yet. (We just create a new timeout (and destroy
}
_hideNotificationCompleted() {
- let notification = this._notification;
+ const notification = this._notification;
this._notification = null;
if (!this._notificationRemoved && notification.isTransient)
notification.destroy(NotificationDestroyedReason.EXPIRED);
setButtons(buttons) {
this.clearButtons();
- for (let buttonInfo of buttons)
+ for (const buttonInfo of buttons)
this.addButton(buttonInfo);
}
if (!this._hasModal)
return;
- let focus = global.stage.key_focus;
+ const focus = global.stage.key_focus;
if (focus && this.contains(focus))
this._savedKeyFocus = focus;
else
this._savedKeyFocus.grab_key_focus();
this._savedKeyFocus = null;
} else {
- let focus = this._initialKeyFocus || this.dialogLayout.initialKeyFocus;
+ const focus = this._initialKeyFocus || this.dialogLayout.initialKeyFocus;
focus.grab_key_focus();
}
}
_updateState() {
- let metadata = {};
- for (let prop in this._playerProxy.Metadata)
+ const metadata = {};
+ for (const prop in this._playerProxy.Metadata)
metadata[prop] = this._playerProxy.Metadata[prop].deepUnpack();
// Validate according to the spec; some clients send buggy metadata:
let [appName, replacesId, appIcon, summary, body, actions, hints, timeout_] = params;
let id;
- for (let hint in hints) {
+ for (const hint in hints) {
// unpack the variants
hints[hint] = hints[hint].deepUnpack();
}
if (actions.length) {
for (let i = 0; i < actions.length - 1; i += 2) {
- let [actionId, label] = [actions[i], actions[i + 1]];
+ const [actionId, label] = [actions[i], actions[i + 1]];
if (actionId === 'default') {
hasDefaultAction = true;
} else {
// of the 'transient' hint with hints['transient'] rather than hints.transient
notification.isTransient = !!hints['transient'];
- let privacyScope = hints['x-gnome-privacy-scope'] || 'user';
+ const privacyScope = hints['x-gnome-privacy-scope'] || 'user';
notification.privacyScope = privacyScope === 'system'
? MessageTray.PrivacyScope.SYSTEM
: MessageTray.PrivacyScope.USER;
this.notify('icon');
}
- let tracker = Shell.WindowTracker.get_default();
+ const tracker = Shell.WindowTracker.get_default();
// Acknowledge notifications that are resident and their app has the
// current focus so that we don't show a banner.
if (notification.resident && this.app && tracker.focus_app === this.app)
} = notification;
if (priority) {
- let urgency = PRIORITY_URGENCY_MAP[priority.unpack()];
+ const urgency = PRIORITY_URGENCY_MAP[priority.unpack()];
this.urgency = urgency !== undefined ? urgency : MessageTray.Urgency.NORMAL;
} else if (urgent) {
this.urgency = urgent.unpack()
}
_onButtonClicked(button) {
- let {action, target} = button;
+ const {action, target} = button;
this._activateAction(action.unpack(), target);
}
}
serialize() {
- let notifications = [];
- for (let notificationId in this._notifications) {
- let notification = this._notifications[notificationId];
+ const notifications = [];
+ for (const notificationId in this._notifications) {
+ const notification = this._notifications[notificationId];
notifications.push([notificationId, notification.serialize()]);
}
return [this._appId, notifications];
this._isLoading = true;
try {
- let value = global.get_persistent_state('a(sa(sv))', 'notifications');
+ const value = global.get_persistent_state('a(sa(sv))', 'notifications');
if (value) {
- let sources = value.deepUnpack();
+ const sources = value.deepUnpack();
sources.forEach(([appId, notifications]) => {
if (notifications.length === 0)
return;
if (this._isLoading)
return;
- let sources = [];
- for (let appId in this._sources) {
- let source = this._sources[appId];
+ const sources = [];
+ for (const appId in this._sources) {
+ const source = this._sources[appId];
sources.push(source.serialize());
}
}
AddNotificationAsync(params, invocation) {
- let [appId, notificationId, notificationSerialized] = params;
+ const [appId, notificationId, notificationSerialized] = params;
let source;
try {
throw e;
}
- let timestamp = GLib.DateTime.new_now_local().to_unix();
+ const timestamp = GLib.DateTime.new_now_local().to_unix();
notificationSerialized['timestamp'] = new GLib.Variant('x', timestamp);
const notification = new GtkNotificationDaemonNotification(source,
}
RemoveNotificationAsync(params, invocation) {
- let [appId, notificationId] = params;
- let source = this._sources[appId];
+ const [appId, notificationId] = params;
+ const source = this._sources[appId];
if (source)
source.removeNotification(notificationId);
}
_position() {
- let workArea = Main.layoutManager.getWorkAreaForMonitor(this._monitor);
+ const workArea = Main.layoutManager.getWorkAreaForMonitor(this._monitor);
if (Clutter.get_default_text_direction() === Clutter.TextDirection.RTL)
this._box.x = workArea.x + (workArea.width - this._box.width);
}
_reset() {
- for (let i in this._osdLabels)
+ for (const i in this._osdLabels)
this._osdLabels[i].destroy();
this._osdLabels = [];
this._monitorLabels = new Map();
- let monitors = Main.layoutManager.monitors;
- for (let i in monitors)
+ const monitors = Main.layoutManager.monitors;
+ for (const i in monitors)
this._monitorLabels.set(monitors[i].index, []);
}
this._reset();
- for (let connector in params) {
- let monitor = this._monitorManager.get_monitor_for_connector(connector);
+ for (const connector in params) {
+ const monitor = this._monitorManager.get_monitor_for_connector(connector);
if (monitor === -1)
continue;
this._monitorLabels.get(monitor).push(params[connector].deepUnpack());
}
- for (let [monitor, labels] of this._monitorLabels.entries()) {
+ for (const [monitor, labels] of this._monitorLabels.entries()) {
labels.sort();
this._osdLabels.push(new OsdMonitorLabel(monitor, labels.join(' ')));
}
});
this._monitorIndex = monitorIndex;
- let constraint = new Layout.MonitorConstraint({index: monitorIndex});
+ const constraint = new Layout.MonitorConstraint({index: monitorIndex});
this.add_constraint(constraint);
this._hbox = new St.BoxLayout({
DND.addDragMonitor(this._dragMonitor);
// Remember the workspace we started from
- let workspaceManager = global.workspace_manager;
+ const workspaceManager = global.workspace_manager;
this._lastActiveWorkspaceIndex = workspaceManager.get_active_workspace_index();
}
// we have to go back to where we started and hide
// the overview
if (this._shown) {
- let workspaceManager = global.workspace_manager;
+ const workspaceManager = global.workspace_manager;
workspaceManager.get_workspace_by_index(this._lastActiveWorkspaceIndex)
.activate(global.get_current_time());
this.hide();
}
_onDragMotion(dragEvent) {
- let targetIsWindow = dragEvent.targetActor &&
+ const targetIsWindow = dragEvent.targetActor &&
dragEvent.targetActor._delegate &&
dragEvent.targetActor._delegate.metaWindow &&
!(dragEvent.targetActor._delegate instanceof WorkspaceThumbnail.WindowClone);
}
_onRestacked() {
- let stack = global.get_window_actors();
- let stackIndices = {};
+ const stack = global.get_window_actors();
+ const stackIndices = {};
for (let i = 0; i < stack.length; i++) {
// Use the stable sequence for an integer to use as a hash key
return true;
if (this._shown) {
- let shouldBeModal = !this._inXdndDrag;
+ const shouldBeModal = !this._inXdndDrag;
if (shouldBeModal && !this._modal) {
if (global.display.is_grabbed()) {
this.hide();
if (!this._shown)
return;
- let event = Clutter.get_current_event();
+ const event = Clutter.get_current_event();
if (event) {
- let type = event.type();
+ const type = event.type();
const button =
type === Clutter.EventType.BUTTON_PRESS ||
type === Clutter.EventType.BUTTON_RELEASE;
- let ctrl = (event.get_state() & Clutter.ModifierType.CONTROL_MASK) !== 0;
+ const ctrl = (event.get_state() & Clutter.ModifierType.CONTROL_MASK) !== 0;
if (button && ctrl)
return;
}
let availableHeight = height;
// Search entry
- let [searchHeight] = this._searchEntry.get_preferred_height(width);
+ const [searchHeight] = this._searchEntry.get_preferred_height(width);
childBox.set_origin(0, startY);
childBox.set_size(width, searchHeight);
this._searchEntry.allocate(childBox);
this.currentDevice = device;
this._padChooserMenu = null;
- let arrow = new St.Icon({
+ const arrow = new St.Icon({
style_class: 'popup-menu-arrow',
icon_name: 'pan-down-symbolic',
accessible_role: Atk.Role.ARROW,
this._menuManager.addMenu(this._padChooserMenu);
for (let i = 0; i < devices.length; i++) {
- let device = devices[i];
+ const device = devices[i];
if (device === this.currentDevice)
continue;
orientation: Clutter.Orientation.HORIZONTAL,
spacing: 6,
});
- let box = new St.Widget({layout_manager: boxLayout});
+ const box = new St.Widget({layout_manager: boxLayout});
this.set_child(box);
this._label = new St.Label({style_class: 'combo-box-label'});
this._buttonItems = [];
- for (let [action, label] of this._actionLabels.entries()) {
- let selectedAction = action;
- let item = this._editMenu.addAction(label, () => {
+ for (const [action, label] of this._actionLabels.entries()) {
+ const selectedAction = action;
+ const item = this._editMenu.addAction(label, () => {
this._onActionSelected(selectedAction);
});
this._actionComboBox.setAction(this._currentAction);
this._updateKeybindingEntryState();
- let isButton = action === null;
+ const isButton = action === null;
this._actionComboBox.setButtonActionsActive(isButton);
}
},
}, class PadDiagram extends St.DrawingArea {
_init(params) {
- let file = Gio.File.new_for_uri('resource:///org/gnome/shell/theme/pad-osd.css');
- let [success_, css] = file.load_contents(null);
+ const file = Gio.File.new_for_uri('resource:///org/gnome/shell/theme/pad-osd.css');
+ const [success_, css] = file.load_contents(null);
this._curEdited = null;
this._css = new TextDecoder().decode(css);
this._labels = [];
}
set image(imagePath) {
- let originalHandle = Rsvg.Handle.new_from_file(imagePath);
- let dimensions = originalHandle.get_dimensions();
+ const originalHandle = Rsvg.Handle.new_from_file(imagePath);
+ const dimensions = originalHandle.get_dimensions();
this._imageWidth = dimensions.width;
this._imageHeight = dimensions.height;
let css = this._css;
for (let i = 0; i < this._activeButtons.length; i++) {
- let ch = String.fromCharCode('A'.charCodeAt() + this._activeButtons[i]);
+ const ch = String.fromCharCode('A'.charCodeAt() + this._activeButtons[i]);
css += `.${ch}.Leader { stroke: ${ACTIVE_COLOR} !important; }`;
css += `.${ch}.Button { stroke: ${ACTIVE_COLOR} !important; fill: ${ACTIVE_COLOR} !important; }`;
}
svgData += this._cssString();
svgData += this._wrappingSvgFooter();
- let istream = new Gio.MemoryInputStream();
+ const istream = new Gio.MemoryInputStream();
istream.add_bytes(new GLib.Bytes(svgData));
return Rsvg.Handle.new_from_stream_sync(istream,
_updateDiagramScale() {
[this._actorWidth, this._actorHeight] = this.get_size();
- let dimensions = this._handle.get_dimensions();
- let scaleX = this._actorWidth / dimensions.width;
- let scaleY = this._actorHeight / dimensions.height;
+ const dimensions = this._handle.get_dimensions();
+ const scaleX = this._actorWidth / dimensions.width;
+ const scaleY = this._actorHeight / dimensions.height;
this._scale = Math.min(scaleX, scaleY);
}
_allocateChild(child, x, y, direction) {
- let [, natHeight] = child.get_preferred_height(-1);
- let [, natWidth] = child.get_preferred_width(natHeight);
- let childBox = new Clutter.ActorBox();
+ const [, natHeight] = child.get_preferred_height(-1);
+ const [, natWidth] = child.get_preferred_width(natHeight);
+ const childBox = new Clutter.ActorBox();
// I miss Cairo.Matrix
- let dimensions = this._handle.get_dimensions();
+ const dimensions = this._handle.get_dimensions();
x = x * this._scale + this._actorWidth / 2 - dimensions.width / 2 * this._scale;
y = y * this._scale + this._actorHeight / 2 - dimensions.height / 2 * this._scale;
if (this._scale == null)
this._updateDiagramScale();
- let [width, height] = this.get_surface_size();
- let dimensions = this._handle.get_dimensions();
- let cr = this.get_context();
+ const [width, height] = this.get_surface_size();
+ const dimensions = this._handle.get_dimensions();
+ const cr = this.get_context();
cr.save();
cr.translate(width / 2, height / 2);
else
direction = RTL;
- let pos = {x: labelPos.x, y: labelPos.y + labelSize.height};
+ const pos = {x: labelPos.x, y: labelPos.y + labelSize.height};
if (this.leftHanded) {
direction = 1 - direction;
pos.x = this._imageWidth - pos.x;
}
_getButtonLabels(button) {
- let ch = String.fromCharCode('A'.charCodeAt() + button);
+ const ch = String.fromCharCode('A'.charCodeAt() + button);
const labelName = `Label${ch}`;
const leaderName = `Leader${ch}`;
return [labelName, leaderName];
}
_getRingLabels(number, dir) {
- let numStr = number > 0 ? (number + 1).toString() : '';
- let dirStr = dir === Meta.PadDirection.CW ? 'CW' : 'CCW';
+ const numStr = number > 0 ? (number + 1).toString() : '';
+ const dirStr = dir === Meta.PadDirection.CW ? 'CW' : 'CCW';
const labelName = `LabelRing${numStr}${dirStr}`;
const leaderName = `LeaderRing${numStr}${dirStr}`;
return [labelName, leaderName];
}
_getStripLabels(number, dir) {
- let numStr = number > 0 ? (number + 1).toString() : '';
- let dirStr = dir === Meta.PadDirection.UP ? 'Up' : 'Down';
+ const numStr = number > 0 ? (number + 1).toString() : '';
+ const dirStr = dir === Meta.PadDirection.UP ? 'Up' : 'Down';
const labelName = `LabelStrip${numStr}${dirStr}`;
const leaderName = `LeaderStrip${numStr}${dirStr}`;
return [labelName, leaderName];
}
_getDialLabels(number, dir) {
- let numStr = number > 0 ? (number + 1).toString() : '';
- let dirStr = dir === Meta.PadDirection.CW ? 'CW' : 'CCW';
+ const numStr = number > 0 ? (number + 1).toString() : '';
+ const dirStr = dir === Meta.PadDirection.CW ? 'CW' : 'CCW';
const labelName = `LabelDial${numStr}${dirStr}`;
const leaderName = `LeaderDial${numStr}${dirStr}`;
return [labelName, leaderName];
}
_addLabel(action, idx, dir) {
- let [found, x, y, arrangement] = this._getLabelCoords(action, idx, dir);
+ const [found, x, y, arrangement] = this._getLabelCoords(action, idx, dir);
if (!found)
return false;
- let label = new St.Label();
+ const label = new St.Label();
this._labels.push({label, action, idx, dir, x, y, arrangement});
this.add_child(label);
return true;
updateLabels(getText) {
for (let i = 0; i < this._labels.length; i++) {
const {label, action, idx, dir} = this._labels[i];
- let str = getText(action, idx, dir);
+ const str = getText(action, idx, dir);
label.set_text(str);
}
Main.uiGroup.add_child(this);
this._monitorIndex = monitorIndex;
- let constraint = new Layout.MonitorConstraint({index: monitorIndex});
+ const constraint = new Layout.MonitorConstraint({index: monitorIndex});
this.add_constraint(constraint);
this._titleBox = new St.BoxLayout({
if (pad === this.padDevice || !this._groupPads.includes(pad))
return;
- let editionMode = this._editionMode;
+ const editionMode = this._editionMode;
this.destroy();
global.display.request_pad_osd(pad, editionMode);
}
}
vfunc_captured_event(event) {
- let isModeSwitch =
+ const isModeSwitch =
(event.type() === Clutter.EventType.PAD_BUTTON_PRESS ||
event.type() === Clutter.EventType.PAD_BUTTON_RELEASE) &&
this.padDevice.get_mode_switch_button_group(event.get_button()) >= 0;
} else if (event.get_source_device() === this.padDevice &&
event.type() === Clutter.EventType.PAD_STRIP) {
if (this._editionMode) {
- let [retval_, number, mode] = event.get_pad_details();
+ const [retval_, number, mode] = event.get_pad_details();
this._startStripActionEdition(number, Meta.PadDirection.UP, mode);
}
} else if (event.get_source_device() === this.padDevice &&
event.type() === Clutter.EventType.PAD_RING) {
if (this._editionMode) {
- let [retval_, number, mode] = event.get_pad_details();
+ const [retval_, number, mode] = event.get_pad_details();
this._startRingActionEdition(number, Meta.PadDirection.CCW, mode);
}
} else if (event.get_source_device() === this.padDevice &&
event.type() === Clutter.EventType.PAD_DIAL) {
if (this._editionMode) {
- let [retval_, number, mode] = event.get_pad_details();
+ const [retval_, number, mode] = event.get_pad_details();
this._startDialActionEdition(number, Meta.PadDirection.CCW, mode);
}
}
}
_startButtonActionEdition(button) {
- let ch = String.fromCharCode('A'.charCodeAt() + button);
- let key = `button${ch}`;
+ const ch = String.fromCharCode('A'.charCodeAt() + button);
+ const key = `button${ch}`;
this._startActionEdition(key, null, button);
}
_startRingActionEdition(ring, dir, mode) {
- let ch = String.fromCharCode('A'.charCodeAt() + ring);
+ const ch = String.fromCharCode('A'.charCodeAt() + ring);
const key = `ring${ch}-${dir === Meta.PadDirection.CCW ? 'ccw' : 'cw'}-mode-${mode}`;
this._startActionEdition(key, Meta.PadFeatureType.RING, ring, dir, mode);
}
_startStripActionEdition(strip, dir, mode) {
- let ch = String.fromCharCode('A'.charCodeAt() + strip);
+ const ch = String.fromCharCode('A'.charCodeAt() + strip);
const key = `strip${ch}-${dir === Meta.PadDirection.UP ? 'up' : 'down'}-mode-${mode}`;
this._startActionEdition(key, Meta.PadFeatureType.STRIP, strip, dir, mode);
}
_startDialActionEdition(dial, dir, mode) {
- let ch = String.fromCharCode('A'.charCodeAt() + dial);
+ const ch = String.fromCharCode('A'.charCodeAt() + dial);
const key = `dial${ch}-${dir === Meta.PadDirection.CCW ? 'ccw' : 'cw'}-mode-${mode}`;
this._startActionEdition(key, Meta.PadFeatureType.DIAL, dial, dir, mode);
}
}
ShowAsync(params, invocation) {
- let [deviceNode, editionMode] = params;
+ const [deviceNode, editionMode] = params;
const seat = global.stage.context.get_backend().get_default_seat();
- let devices = seat.list_devices();
+ const devices = seat.list_devices();
let padDevice = null;
devices.forEach(device => {
Signals: {'page-activated': {param_types: [GObject.TYPE_INT]}},
}, class PageIndicators extends St.BoxLayout {
_init(orientation = Clutter.Orientation.VERTICAL) {
- let vertical = orientation === Clutter.Orientation.VERTICAL;
+ const vertical = orientation === Clutter.Orientation.VERTICAL;
super._init({
style_class: 'page-indicators',
orientation,
// natural height, so we chain up to St.BoxLayout, but we only request 0
// as minimum height, since it's not that important if some indicators
// are not shown
- let [, natHeight] = super.vfunc_get_preferred_height(forWidth);
+ const [, natHeight] = super.vfunc_get_preferred_height(forWidth);
return [0, natHeight];
}
setReactive(reactive) {
- let children = this.get_children();
+ const children = this.get_children();
for (let i = 0; i < children.length; i++)
children[i].reactive = reactive;
if (this._nPages === nPages)
return;
- let diff = nPages - this._nPages;
+ const diff = nPages - this._nPages;
if (diff > 0) {
for (let i = 0; i < diff; i++) {
- let pageIndex = this._nPages + i;
+ const pageIndex = this._nPages + i;
const indicator = new St.Button({
style_class: 'page-indicator',
button_mask: St.ButtonMask.ONE |
this.add_child(indicator);
}
} else {
- let children = this.get_children().splice(diff);
+ const children = this.get_children().splice(diff);
for (let i = 0; i < children.length; i++)
children[i].destroy();
}
}
_updateIndicator(indicator, pageIndex) {
- let progress =
+ const progress =
Math.max(1 - Math.abs(this._currentPosition - pageIndex), 0);
- let inactiveScale = indicator.pressed
+ const inactiveScale = indicator.pressed
? INDICATOR_INACTIVE_SCALE_PRESSED : INDICATOR_INACTIVE_SCALE;
- let inactiveOpacity = indicator.hover
+ const inactiveOpacity = indicator.hover
? INDICATOR_INACTIVE_OPACITY_HOVER : INDICATOR_INACTIVE_OPACITY;
- let scale = inactiveScale + (1 - inactiveScale) * progress;
- let opacity = inactiveOpacity + (255 - inactiveOpacity) * progress;
+ const scale = inactiveScale + (1 - inactiveScale) * progress;
+ const opacity = inactiveOpacity + (255 - inactiveOpacity) * progress;
indicator.child.set_scale(scale, scale);
indicator.child.opacity = opacity;
setCurrentPosition(currentPosition) {
this._currentPosition = currentPosition;
- let children = this.get_children();
+ const children = this.get_children();
for (let i = 0; i < children.length; i++)
this._updateIndicator(children[i], i);
}
}
vfunc_key_release_event(event) {
- let symbol = event.get_key_symbol();
+ const symbol = event.get_key_symbol();
if (symbol === Clutter.KEY_Return || symbol === Clutter.KEY_space) {
if (Main.overview.shouldToggleByCornerOrButton()) {
Main.overview.toggle();
}
_xdndToggleOverview() {
- let [x, y] = global.get_pointer();
- let pickedActor = global.stage.get_actor_at_pos(Clutter.PickMode.REACTIVE, x, y);
+ const [x, y] = global.get_pointer();
+ const pickedActor = global.stage.get_actor_at_pos(Clutter.PickMode.REACTIVE, x, y);
if (pickedActor === this && Main.overview.shouldToggleByCornerOrButton())
Main.overview.toggle();
}
vfunc_get_preferred_width(_forHeight) {
- let primaryMonitor = Main.layoutManager.primaryMonitor;
+ const primaryMonitor = Main.layoutManager.primaryMonitor;
if (primaryMonitor)
return [0, primaryMonitor.width];
vfunc_allocate(box) {
this.set_allocation(box);
- let allocWidth = box.x2 - box.x1;
- let allocHeight = box.y2 - box.y1;
+ const allocWidth = box.x2 - box.x1;
+ const allocHeight = box.y2 - box.y1;
- let [, leftNaturalWidth] = this._leftBox.get_preferred_width(-1);
- let [, centerNaturalWidth] = this._centerBox.get_preferred_width(-1);
- let [, rightNaturalWidth] = this._rightBox.get_preferred_width(-1);
+ const [, leftNaturalWidth] = this._leftBox.get_preferred_width(-1);
+ const [, centerNaturalWidth] = this._centerBox.get_preferred_width(-1);
+ const [, rightNaturalWidth] = this._rightBox.get_preferred_width(-1);
- let sideWidth, centerWidth;
- centerWidth = centerNaturalWidth;
+ const centerWidth = centerNaturalWidth;
// get workspace area and center date entry relative to it
- let monitor = Main.layoutManager.findMonitorForActor(this);
+ const monitor = Main.layoutManager.findMonitorForActor(this);
let centerOffset = 0;
if (monitor) {
- let workArea = Main.layoutManager.getWorkAreaForMonitor(monitor.index);
+ const workArea = Main.layoutManager.getWorkAreaForMonitor(monitor.index);
centerOffset = 2 * (workArea.x - monitor.x) + workArea.width - monitor.width;
}
- sideWidth = Math.max(0, (allocWidth - centerWidth + centerOffset) / 2);
+ const sideWidth = Math.max(0, (allocWidth - centerWidth + centerOffset) / 2);
- let childBox = new Clutter.ActorBox();
+ const childBox = new Clutter.ActorBox();
childBox.y1 = 0;
childBox.y2 = allocHeight;
return Clutter.EVENT_PROPAGATE;
const [x, y] = event.get_coords();
- let dragWindow = this._getDraggableWindowForPosition(x);
+ const dragWindow = this._getDraggableWindowForPosition(x);
if (!dragWindow)
return Clutter.EVENT_PROPAGATE;
}
vfunc_key_press_event(event) {
- let symbol = event.get_key_symbol();
+ const symbol = event.get_key_symbol();
if (symbol === Clutter.KEY_Escape) {
global.display.focus_default_window(event.get_time());
return Clutter.EVENT_STOP;
if (!indicator || !indicator.mapped)
return; // menu not supported by current session mode
- let menu = indicator.menu;
+ const menu = indicator.menu;
if (!indicator.reactive)
return;
}
set boxOpacity(value) {
- let isReactive = value > 0;
+ const isReactive = value > 0;
this._leftBox.opacity = value;
this._leftBox.reactive = isReactive;
}
_updatePanel() {
- let panel = Main.sessionMode.panel;
+ const panel = Main.sessionMode.panel;
this._hideIndicators();
this._updateBox(panel.left, this._leftBox);
this._updateBox(panel.center, this._centerBox);
}
_hideIndicators() {
- for (let role in PANEL_ITEM_IMPLEMENTATIONS) {
- let indicator = this.statusArea[role];
+ for (const role in PANEL_ITEM_IMPLEMENTATIONS) {
+ const indicator = this.statusArea[role];
if (!indicator)
continue;
indicator.container.hide();
_ensureIndicator(role) {
let indicator = this.statusArea[role];
if (!indicator) {
- let constructor = PANEL_ITEM_IMPLEMENTATIONS[role];
+ const constructor = PANEL_ITEM_IMPLEMENTATIONS[role];
if (!constructor) {
// This icon is not implemented (this is a bug)
return null;
}
_updateBox(elements, box) {
- let nChildren = box.get_n_children();
+ const nChildren = box.get_n_children();
for (let i = 0; i < elements.length; i++) {
- let role = elements[i];
- let indicator = this._ensureIndicator(role);
+ const role = elements[i];
+ const indicator = this._ensureIndicator(role);
if (indicator == null)
continue;
}
_addToPanelBox(role, indicator, position, box) {
- let container = indicator.container;
+ const container = indicator.container;
container.show();
- let parent = container.get_parent();
+ const parent = container.get_parent();
if (parent)
parent.remove_child(container);
box.insert_child_at_index(container, position);
this.statusArea[role] = indicator;
- let destroyId = indicator.connect('destroy', emitter => {
+ const destroyId = indicator.connect('destroy', emitter => {
delete this.statusArea[role];
emitter.disconnect(destroyId);
});
throw new TypeError('Status indicator must be an instance of PanelMenu.Button');
position ??= 0;
- let boxes = {
+ const boxes = {
left: this._leftBox,
center: this._centerBox,
right: this._rightBox,
};
- let boxContainer = boxes[box] || this._rightBox;
+ const boxContainer = boxes[box] || this._rightBox;
this.statusArea[role] = indicator;
this._addToPanelBox(role, indicator, position, boxContainer);
return indicator;
}
_getDraggableWindowForPosition(stageX) {
- let workspaceManager = global.workspace_manager;
+ const workspaceManager = global.workspace_manager;
const windows = workspaceManager.get_active_workspace().list_windows();
const allWindowsByStacking =
global.display.sort_windows_by_stacking(windows).reverse();
return allWindowsByStacking.find(metaWindow => {
- let rect = metaWindow.get_frame_rect();
+ const rect = metaWindow.get_frame_rect();
return metaWindow.is_on_primary_monitor() &&
metaWindow.showing_on_its_workspace() &&
metaWindow.get_window_type() !== Meta.WindowType.DESKTOP &&
}
_onStyleChanged(actor) {
- let themeNode = actor.get_theme_node();
+ const themeNode = actor.get_theme_node();
this._minHPadding = themeNode.get_length('-minimum-hpadding');
this._natHPadding = themeNode.get_length('-natural-hpadding');
}
vfunc_get_preferred_width(_forHeight) {
- let child = this.get_first_child();
+ const child = this.get_first_child();
let minimumSize, naturalSize;
if (child)
}
vfunc_get_preferred_height(_forWidth) {
- let child = this.get_first_child();
+ const child = this.get_first_child();
if (child)
return child.get_preferred_height(-1);
vfunc_allocate(box) {
this.set_allocation(box);
- let child = this.get_first_child();
+ const child = this.get_first_child();
if (!child)
return;
- let [, natWidth] = child.get_preferred_width(-1);
+ const [, natWidth] = child.get_preferred_width(-1);
- let availWidth = box.x2 - box.x1;
- let availHeight = box.y2 - box.y1;
+ const availWidth = box.x2 - box.x1;
+ const availHeight = box.y2 - box.y1;
- let childBox = new Clutter.ActorBox();
+ const childBox = new Clutter.ActorBox();
if (natWidth + 2 * this._natHPadding <= availWidth) {
childBox.x1 = this._natHPadding;
childBox.x2 = availWidth - this._natHPadding;
if (global.focus_manager.navigate_from_event(event))
return Clutter.EVENT_STOP;
- let symbol = event.get_key_symbol();
+ const symbol = event.get_key_symbol();
if (symbol === Clutter.KEY_Left || symbol === Clutter.KEY_Right) {
- let group = global.focus_manager.get_group(this);
+ const group = global.focus_manager.get_group(this);
if (group) {
- let direction = symbol === Clutter.KEY_Left ? St.DirectionType.LEFT : St.DirectionType.RIGHT;
+ const direction = symbol === Clutter.KEY_Left ? St.DirectionType.LEFT : St.DirectionType.RIGHT;
group.navigate_focus(this, direction, false);
return Clutter.EVENT_STOP;
}
// Setting the max-height won't do any good if the minimum height of the
// menu is higher then the screen; it's useful if part of the menu is
// scrollable so the minimum height is smaller than the natural height
- let workArea = Main.layoutManager.getWorkAreaForMonitor(Main.layoutManager.primaryIndex);
- let scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
- let verticalMargins = this.menu.actor.margin_top + this.menu.actor.margin_bottom;
+ const workArea = Main.layoutManager.getWorkAreaForMonitor(Main.layoutManager.primaryIndex);
+ const scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
+ const verticalMargins = this.menu.actor.margin_top + this.menu.actor.margin_bottom;
// The workarea and margin dimensions are in physical pixels, but CSS
// measures are in logical pixels, so make sure to consider the scale
// factor when computing max-height
- let maxHeight = Math.round((workArea.height - verticalMargins) / scaleFactor);
+ const maxHeight = Math.round((workArea.height - verticalMargins) / scaleFactor);
this.menu.actor.style = `max-height: ${maxHeight}px;`;
}
}
vfunc_repaint() {
- let node = this.get_theme_node();
- let backgroundColor = node.get_color('-pie-background-color');
- let borderColor = node.get_color('-pie-border-color');
- let borderWidth = node.get_length('-pie-border-width');
- let [width, height] = this.get_surface_size();
- let radius = Math.min(width / 2, height / 2);
+ const node = this.get_theme_node();
+ const backgroundColor = node.get_color('-pie-background-color');
+ const borderColor = node.get_color('-pie-border-color');
+ const borderWidth = node.get_length('-pie-border-width');
+ const [width, height] = this.get_surface_size();
+ const radius = Math.min(width / 2, height / 2);
- let startAngle = 3 * Math.PI / 2;
- let endAngle = startAngle + this._angle;
+ const startAngle = 3 * Math.PI / 2;
+ const endAngle = startAngle + this._angle;
- let cr = this.get_context();
+ const cr = this.get_context();
cr.setLineCap(Cairo.LineCap.ROUND);
cr.setLineJoin(Cairo.LineJoin.ROUND);
cr.translate(width / 2, height / 2);
const seat = global.stage.context.get_backend().get_default_seat();
seat.connect('ptr-a11y-timeout-started', (o, type, timeout) => {
- let [x, y] = global.get_pointer();
+ const [x, y] = global.get_pointer();
this._pieTimer = new PieTimer();
Main.uiGroup.add_child(this._pieTimer);
// Avoid unreliably calling the watch for the current position
this._updatePointer();
- let watch = new PointerWatch(this, interval, callback);
+ const watch = new PointerWatch(this, interval, callback);
this._watches.push(watch);
this._updateTimeout();
return watch;
}
_updatePointer() {
- let [x, y] = global.get_pointer();
+ const [x, y] = global.get_pointer();
if (this.pointerX === x && this.pointerY === y)
return;
this.pointerY = y;
for (let i = 0; i < this._watches.length;) {
- let watch = this._watches[i];
+ const watch = this._watches[i];
watch.callback(x, y);
if (watch === this._watches[i]) // guard against self-removal
i++;
if (state)
return Clutter.EVENT_PROPAGATE;
- let symbol = event.get_key_symbol();
+ const symbol = event.get_key_symbol();
if (symbol === Clutter.KEY_space || symbol === Clutter.KEY_Return) {
this.activate(event);
return Clutter.EVENT_STOP;
}
set active(active) {
- let activeChanged = active !== this.active;
+ const activeChanged = active !== this.active;
if (activeChanged) {
this._active = active;
if (active) {
}
syncSensitive() {
- let sensitive = this.sensitive;
+ const sensitive = this.sensitive;
this.reactive = sensitive;
this.can_focus = sensitive;
this.notify('sensitive');
_motionEvent(actor, event) {
this._dragged = true;
- let [absX] = event.get_coords();
- let factorDiff = (absX - this._initialGrabX) / (this.get_width() - this._handle.get_width());
- let factor = factorDiff + (this.state ? 1.0 : 0.0);
+ const [absX] = event.get_coords();
+ const factorDiff = (absX - this._initialGrabX) / (this.get_width() - this._handle.get_width());
+ const factor = factorDiff + (this.state ? 1.0 : 0.0);
this._handleAlignConstraint.set_factor(Math.clamp(factor, 0, 1));
}
addSettingsAction(title, desktopFile) {
- let menuItem = this.addAction(title, () => {
- let app = Shell.AppSystem.get_default().lookup_app(desktopFile);
+ const menuItem = this.addAction(title, () => {
+ const app = Shell.AppSystem.get_default().lookup_app(desktopFile);
if (!app) {
log(`Settings panel for desktop file ${desktopFile} could not be loaded!`);
}
_setSettingsVisibility(visible) {
- for (let id in this._settingsActions) {
- let item = this._settingsActions[id];
+ for (const id in this._settingsActions) {
+ const item = this._settingsActions[id];
item.visible = visible;
}
}
isEmpty() {
- let hasVisibleChildren = this.box.get_children().some(child => {
+ const hasVisibleChildren = this.box.get_children().some(child => {
if (child._delegate instanceof PopupSeparatorMenuItem)
return false;
return isPopupMenuItemVisible(child);
if (menuItem.label.text)
return;
- let children = this.box.get_children();
+ const children = this.box.get_children();
- let index = children.indexOf(menuItem.actor);
+ const index = children.indexOf(menuItem.actor);
if (index < 0)
return;
}
moveMenuItem(menuItem, position) {
- let items = this._getMenuItems();
+ const items = this._getMenuItems();
let i = 0;
while (i < items.length && position > 0) {
if (position === undefined) {
this.box.add_child(menuItem.actor);
} else {
- let items = this._getMenuItems();
+ const items = this._getMenuItems();
if (position < items.length) {
beforeItem = items[position].actor;
this.box.insert_child_below(menuItem.actor, beforeItem);
}
get firstMenuItem() {
- let items = this._getMenuItems();
+ const items = this._getMenuItems();
if (items.length)
return items[0];
else
}
removeAll() {
- let children = this._getMenuItems();
+ const children = this._getMenuItems();
for (let i = 0; i < children.length; i++) {
- let item = children[i];
+ const item = children[i];
item.destroy();
}
}
if (state)
return Clutter.EVENT_PROPAGATE;
- let symbol = event.get_key_symbol();
+ const symbol = event.get_key_symbol();
if (symbol === Clutter.KEY_space || symbol === Clutter.KEY_Return) {
this.toggle();
}
_needsScrollbar() {
- let topMenu = this._getTopMenu();
- let [, topNaturalHeight] = topMenu.actor.get_preferred_height(-1);
- let topThemeNode = topMenu.actor.get_theme_node();
+ const topMenu = this._getTopMenu();
+ const [, topNaturalHeight] = topMenu.actor.get_preferred_height(-1);
+ const topThemeNode = topMenu.actor.get_theme_node();
- let topMaxHeight = topThemeNode.get_max_height();
+ const topMaxHeight = topThemeNode.get_max_height();
return topMaxHeight >= 0 && topNaturalHeight >= topMaxHeight;
}
this.actor.show();
- let needsScrollbar = this._needsScrollbar();
+ const needsScrollbar = this._needsScrollbar();
// St.ScrollView always requests space horizontally for a possible vertical
// scrollbar if in AUTOMATIC mode. Doing better would require implementation
if (animate && needsScrollbar)
animate = false;
- let targetAngle = this.actor.text_direction === Clutter.TextDirection.RTL ? -90 : 90;
+ const targetAngle = this.actor.text_direction === Clutter.TextDirection.RTL ? -90 : 90;
const duration = animate ? 250 : 0;
- let [, naturalHeight] = this.actor.get_preferred_height(-1);
+ const [, naturalHeight] = this.actor.get_preferred_height(-1);
this.actor.height = 0;
this.actor.ease({
height: naturalHeight,
this.add_child(this.label);
this.label_actor = this.label;
- let expander = new St.Bin({
+ const expander = new St.Bin({
style_class: 'popup-menu-item-expander',
x_expand: true,
});
}
syncSensitive() {
- let sensitive = super.syncSensitive();
+ const sensitive = super.syncSensitive();
this._triangle.visible = sensitive;
if (!sensitive)
this.menu.close(false);
}
vfunc_key_press_event(event) {
- let symbol = event.get_key_symbol();
+ const symbol = event.get_key_symbol();
if (symbol === Clutter.KEY_Right) {
this._setOpenState(true);
if (!this.activeMenu)
return;
- let actor = global.stage.get_key_focus();
- let newMenu = this._findMenuForSource(actor);
+ const actor = global.stage.get_key_focus();
+ const newMenu = this._findMenuForSource(actor);
if (newMenu)
this._changeMenu(newMenu);
}
_onCapturedEvent(actor, event) {
- let menu = actor._delegate;
+ const menu = actor._delegate;
const targetActor = global.stage.get_event_actor(event);
if (event.type() === Clutter.EventType.KEY_PRESS) {
- let symbol = event.get_key_symbol();
+ const symbol = event.get_key_symbol();
if (symbol === Clutter.KEY_Down &&
global.stage.get_key_focus() === menu.actor) {
actor.navigate_focus(null, St.DirectionType.TAB_FORWARD, false);
}
} else if (event.type() === Clutter.EventType.ENTER &&
(event.get_flags() & Clutter.EventFlags.FLAG_GRAB_NOTIFY) === 0) {
- let hoveredMenu = this._findMenuForSource(targetActor);
+ const hoveredMenu = this._findMenuForSource(targetActor);
if (hoveredMenu && hoveredMenu !== menu)
this._changeMenu(hoveredMenu);
_findMenuForSource(source) {
while (source) {
- let actor = source;
+ const actor = source;
const menu = this._menus.find(m => m.sourceActor === actor);
if (menu)
return menu;
});
this._box.add_child(contents);
- let separator = new St.Widget({style_class: 'quick-toggle-separator'});
+ const separator = new St.Widget({style_class: 'quick-toggle-separator'});
this._box.add_child(separator);
this._menuButton = new St.Button({
* @returns {RemoteSearchProvider[]} - the list of remote providers
*/
export function loadRemoteSearchProviders(searchSettings) {
- let objectPaths = {};
+ const objectPaths = {};
let loadedProviders = [];
function loadRemoteSearchProvider(file) {
- let keyfile = new GLib.KeyFile();
- let path = file.get_path();
+ const keyfile = new GLib.KeyFile();
+ const path = file.get_path();
try {
keyfile.load_from_file(path, 0);
let remoteProvider;
try {
- let group = KEY_FILE_GROUP;
- let busName = keyfile.get_string(group, 'BusName');
- let objectPath = keyfile.get_string(group, 'ObjectPath');
+ const group = KEY_FILE_GROUP;
+ const busName = keyfile.get_string(group, 'BusName');
+ const objectPath = keyfile.get_string(group, 'ObjectPath');
if (objectPaths[objectPath])
return;
let appInfo = null;
try {
- let desktopId = keyfile.get_string(group, 'DesktopId');
+ const desktopId = keyfile.get_string(group, 'DesktopId');
appInfo = GioUnix.DesktopAppInfo.new(desktopId);
if (!appInfo.should_show())
return;
for (const {file} of FileUtils.collectFromDatadirs('search-providers', false))
loadRemoteSearchProvider(file);
- let sortOrder = searchSettings.get_strv('sort-order');
+ const sortOrder = searchSettings.get_strv('sort-order');
const disabled = searchSettings.get_strv('disabled');
const enabled = searchSettings.get_strv('enabled');
loadedProviders = loadedProviders.filter(provider => {
- let appId = provider.appInfo.get_id();
+ const appId = provider.appInfo.get_id();
if (provider.defaultEnabled)
return !disabled.includes(appId);
});
loadedProviders.sort((providerA, providerB) => {
- let idxA, idxB;
- let appIdA, appIdB;
+ const appIdA = providerA.appInfo.get_id();
+ const appIdB = providerB.appInfo.get_id();
- appIdA = providerA.appInfo.get_id();
- appIdB = providerB.appInfo.get_id();
-
- idxA = sortOrder.indexOf(appIdA);
- idxB = sortOrder.indexOf(appIdB);
+ const idxA = sortOrder.indexOf(appIdA);
+ const idxB = sortOrder.indexOf(appIdB);
// if no provider is found in the order, use alphabetical order
if ((idxA === -1) && (idxB === -1)) {
- let nameA = providerA.appInfo.get_name();
- let nameB = providerB.appInfo.get_name();
+ const nameA = providerA.appInfo.get_name();
+ const nameB = providerB.appInfo.get_name();
return GLib.utf8_collate(nameA, nameB);
}
if (results.length <= maxNumber)
return results;
- let regularResults = results.filter(r => !r.startsWith('special:'));
- let specialResults = results.filter(r => r.startsWith('special:'));
+ const regularResults = results.filter(r => !r.startsWith('special:'));
+ const specialResults = results.filter(r => r.startsWith('special:'));
return regularResults.slice(0, maxNumber).concat(specialResults.slice(0, maxNumber));
}
return [];
}
- let resultMetas = [];
+ const resultMetas = [];
for (let i = 0; i < metas.length; i++) {
- for (let prop in metas[i]) {
+ for (const prop in metas[i]) {
// we can use the serialized icon variant directly
if (prop !== 'icon')
metas[i][prop] = metas[i][prop].deepUnpack();
},
};
- let title = _('Run a Command');
+ const title = _('Run a Command');
- let content = new Dialog.MessageDialogContent({title});
+ const content = new Dialog.MessageDialogContent({title});
this.contentLayout.add_child(content);
const [labelActor] = content;
- let entry = new St.Entry({
+ const entry = new St.Entry({
style_class: 'run-dialog-entry',
labelActor,
can_focus: true,
content.add_child(entry);
this.setInitialKeyFocus(this._entryText);
- let defaultDescriptionText = _('Press ESC to close');
+ const defaultDescriptionText = _('Press ESC to close');
this._descriptionLabel = new St.Label({
style_class: 'run-dialog-description',
entry: this._entryText,
});
this._entryText.connect('key-press-event', (o, e) => {
- let symbol = e.get_key_symbol();
+ const symbol = e.get_key_symbol();
if (symbol === Clutter.KEY_Tab) {
- let text = o.get_text();
+ const text = o.get_text();
let prefix;
if (text.lastIndexOf(' ') === -1)
prefix = text;
else
prefix = text.substring(text.lastIndexOf(' ') + 1);
- let postfix = this._getCompletion(prefix);
+ const postfix = this._getCompletion(prefix);
if (postfix != null && postfix.length > 0) {
o.insert_text(postfix, -1);
o.set_cursor_position(text.length + postfix.length);
return s1.substring(0, k);
}
- let paths = GLib.getenv('PATH').split(':');
+ const paths = GLib.getenv('PATH').split(':');
paths.push(GLib.get_home_dir());
- let someResults = paths.map(path => {
- let results = [];
+ const someResults = paths.map(path => {
+ const results = [];
try {
- let file = Gio.File.new_for_path(path);
- let fileEnum = file.enumerate_children('standard::name', Gio.FileQueryInfoFlags.NONE, null);
+ const file = Gio.File.new_for_path(path);
+ const fileEnum = file.enumerate_children('standard::name', Gio.FileQueryInfoFlags.NONE, null);
let info;
while ((info = fileEnum.next_file(null))) {
- let name = info.get_name();
+ const name = info.get_name();
if (name.slice(0, text.length) === text)
results.push(name);
}
}
return results;
});
- let results = someResults.reduce((a, b) => a.concat(b), []);
+ const results = someResults.reduce((a, b) => a.concat(b), []);
if (!results.length)
return null;
- let common = results.reduce(_getCommon, null);
+ const common = results.reduce(_getCommon, null);
return common.substring(text.length);
}
} else {
try {
if (inTerminal) {
- let exec = this._terminalSettings.get_string(EXEC_KEY);
- let execArg = this._terminalSettings.get_string(EXEC_ARG_KEY);
+ const exec = this._terminalSettings.get_string(EXEC_KEY);
+ const execArg = this._terminalSettings.get_string(EXEC_ARG_KEY);
command = `${exec} ${execArg} ${input}`;
}
Util.trySpawnCommandLine(command);
}
if (path && GLib.file_test(path, GLib.FileTest.EXISTS)) {
- let file = Gio.file_new_for_path(path);
+ const file = Gio.file_new_for_path(path);
try {
Gio.app_info_launch_default_for_uri(file.get_uri(),
global.create_app_launch_context(0, -1));
// Error invoking Gio.app_info_launch_default_for_uri: No application
// is registered as handling this file
// We are only interested in the part after the first colon.
- let message = err.message.replace(/[^:]*: *(.+)/, '$1');
+ const message = err.message.replace(/[^:]*: *(.+)/, '$1');
this._showError(message);
}
} else {
}
_setActive(active) {
- let prevIsActive = this._isActive;
+ const prevIsActive = this._isActive;
this._isActive = active;
if (prevIsActive !== this._isActive)
}
_setLocked(locked) {
- let prevIsLocked = this._isLocked;
+ const prevIsLocked = this._isLocked;
this._isLocked = locked;
if (prevIsLocked !== this._isLocked)
if (this._isModal)
return true;
- let grab = Main.pushModal(Main.uiGroup, {actionMode: Shell.ActionMode.LOCK_SCREEN});
+ const grab = Main.pushModal(Main.uiGroup, {actionMode: Shell.ActionMode.LOCK_SCREEN});
// We expect at least a keyboard grab here
this._isModal = (grab.get_seat_state() & Clutter.GrabState.KEYBOARD) !== 0;
if (this._activationTime === 0)
this._activationTime = GLib.get_monotonic_time();
- let shouldLock = this._settings.get_boolean(LOCK_ENABLED_KEY) && !this._isLocked;
+ const shouldLock = this._settings.get_boolean(LOCK_ENABLED_KEY) && !this._isLocked;
if (shouldLock) {
- let lockTimeout = Math.max(
+ const lockTimeout = Math.max(
adjustAnimationTime(STANDARD_FADE_TIME),
this._settings.get_uint(LOCK_DELAY_KEY) * 1000);
this._lockTimeoutId = GLib.timeout_add(
_ensureUnlockDialog(allowCancel) {
if (!this._dialog) {
- let constructor = Main.sessionMode.unlockDialog;
+ const constructor = Main.sessionMode.unlockDialog;
if (!constructor) {
// This session mode has no locking capabilities
this.deactivate(true);
this._lockScreenGroup.show();
this._lockScreenState = MessageTray.State.SHOWING;
- let fadeToBlack = params.fadeToBlack;
+ const fadeToBlack = params.fadeToBlack;
if (params.animateLockScreen) {
this._lockDialogGroup.translation_y = -global.screen_height;
if (params.fadeToBlack && params.animateFade) {
// Take a beat
- let id = GLib.timeout_add(GLib.PRIORITY_DEFAULT, MANUAL_FADE_TIME, () => {
+ const id = GLib.timeout_add(GLib.PRIORITY_DEFAULT, MANUAL_FADE_TIME, () => {
this._activateFade(this._shortLightbox, MANUAL_FADE_TIME);
return GLib.SOURCE_REMOVE;
});
}
removeCredentialManager(serviceName) {
- let credentialManager = this._credentialManagers[serviceName];
+ const credentialManager = this._credentialManagers[serviceName];
if (!credentialManager)
return;
St.Clipboard.get_default().set_text(St.ClipboardType.CLIPBOARD, '');
St.Clipboard.get_default().set_text(St.ClipboardType.PRIMARY, '');
- let userManager = AccountsService.UserManager.get_default();
- let user = userManager.get_user(GLib.get_user_name());
+ const userManager = AccountsService.UserManager.get_default();
+ const user = userManager.get_user(GLib.get_user_name());
this.activate(animate);
lockIfWasLocked() {
if (!this._settings.get_boolean(LOCK_ENABLED_KEY))
return;
- let wasLocked = global.get_runtime_state('b', LOCKED_STATE_STR);
+ const wasLocked = global.get_runtime_state('b', LOCKED_STATE_STR);
if (wasLocked === null)
return;
const laters = global.compositor.get_laters();
const nSlots = this._windowSlots.length;
for (let i = 0; i < nSlots; i++) {
- let [x, y, width, height, child] = this._windowSlots[i];
+ const [x, y, width, height, child] = this._windowSlots[i];
childBox.set_origin(x, y);
childBox.set_size(width, height);
capture() {
for (const actor of global.get_window_actors()) {
- let window = actor.metaWindow;
- let workspaceManager = global.workspace_manager;
- let activeWorkspace = workspaceManager.get_active_workspace();
+ const window = actor.metaWindow;
+ const workspaceManager = global.workspace_manager;
+ const activeWorkspace = workspaceManager.get_active_workspace();
if (window.is_override_redirect() ||
!window.located_on_workspace(activeWorkspace) ||
window.get_monitor() !== this._monitorIndex)
if (needsDisk)
lockedDown = this._lockdownSettings.get_boolean('disable-save-to-disk');
- let sender = invocation.get_sender();
+ const sender = invocation.get_sender();
if (this._screenShooter.has(sender)) {
invocation.return_error_literal(
Gio.IOErrorEnum, Gio.IOErrorEnum.BUSY,
}
}
- let shooter = new Shell.Screenshot();
+ const shooter = new Shell.Screenshot();
shooter._watchNameId = Gio.bus_watch_name(Gio.BusType.SESSION,
sender, 0, null, this._onNameVanished.bind(this));
}
_removeShooterForSender(sender) {
- let shooter = this._screenShooter.get(sender);
+ const shooter = this._screenShooter.get(sender);
if (!shooter)
return;
*_resolveRelativeFilename(filename) {
filename = filename.replace(/\.png$/, '');
- let path = [
+ const path = [
GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_PICTURES),
GLib.get_home_dir(),
].find(p => p && GLib.file_test(p, GLib.FileTest.EXISTS));
if (GLib.path_is_absolute(filename)) {
try {
- let file = Gio.File.new_for_path(filename);
- let stream = file.replace(null, false, Gio.FileCreateFlags.NONE, null);
+ const file = Gio.File.new_for_path(filename);
+ const stream = file.replace(null, false, Gio.FileCreateFlags.NONE, null);
return [stream, file];
} catch (e) {
invocation.return_gerror(e);
}
let err;
- for (let file of this._resolveRelativeFilename(filename)) {
+ for (const file of this._resolveRelativeFilename(filename)) {
try {
- let stream = file.create(Gio.FileCreateFlags.NONE, null);
+ const stream = file.create(Gio.FileCreateFlags.NONE, null);
return [stream, file];
} catch (e) {
err = e;
if (file) {
filenameUsed = file.get_path();
} else {
- let bytes = stream.steal_as_bytes();
- let clipboard = St.Clipboard.get_default();
+ const bytes = stream.steal_as_bytes();
+ const clipboard = St.Clipboard.get_default();
clipboard.set_content(St.ClipboardType.CLIPBOARD, 'image/png', bytes);
}
- let retval = GLib.Variant.new('(bs)', [true, filenameUsed]);
+ const retval = GLib.Variant.new('(bs)', [true, filenameUsed]);
invocation.return_value(retval);
}
_scaleArea(x, y, width, height) {
- let scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
+ const scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
x *= scaleFactor;
y *= scaleFactor;
width *= scaleFactor;
}
_unscaleArea(x, y, width, height) {
- let scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
+ const scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
x /= scaleFactor;
y /= scaleFactor;
width /= scaleFactor;
'Invalid params');
return;
}
- let screenshot = await this._createScreenshot(invocation);
+ const screenshot = await this._createScreenshot(invocation);
if (!screenshot)
return;
- let [stream, file] = this._createStream(filename, invocation);
+ const [stream, file] = this._createStream(filename, invocation);
if (!stream)
return;
}
async ScreenshotWindowAsync(params, invocation) {
- let [includeFrame, includeCursor, flash, filename] = params;
- let screenshot = await this._createScreenshot(invocation);
+ const [includeFrame, includeCursor, flash, filename] = params;
+ const screenshot = await this._createScreenshot(invocation);
if (!screenshot)
return;
- let [stream, file] = this._createStream(filename, invocation);
+ const [stream, file] = this._createStream(filename, invocation);
if (!stream)
return;
}
async ScreenshotAsync(params, invocation) {
- let [includeCursor, flash, filename] = params;
- let screenshot = await this._createScreenshot(invocation);
+ const [includeCursor, flash, filename] = params;
+ const screenshot = await this._createScreenshot(invocation);
if (!screenshot)
return;
- let [stream, file] = this._createStream(filename, invocation);
+ const [stream, file] = this._createStream(filename, invocation);
if (!stream)
return;
return;
}
- let selectArea = new SelectArea();
+ const selectArea = new SelectArea();
try {
- let areaRectangle = await selectArea.selectAsync();
- let retRectangle = this._unscaleArea(
+ const areaRectangle = await selectArea.selectAsync();
+ const retRectangle = this._unscaleArea(
areaRectangle.x, areaRectangle.y,
areaRectangle.width, areaRectangle.height);
invocation.return_value(GLib.Variant.new('(iiii)', retRectangle));
'Invalid params');
return;
}
- let flashspot = new Flashspot({x, y, width, height});
+ const flashspot = new Flashspot({x, y, width, height});
flashspot.fire();
invocation.return_value(null);
}
[this._lastX, this._lastY] = event.get_coords();
this._lastX = Math.floor(this._lastX);
this._lastY = Math.floor(this._lastY);
- let geometry = this._getGeometry();
+ const geometry = this._getGeometry();
this._rubberband.set_position(geometry.x, geometry.y);
this._rubberband.set_size(geometry.width, geometry.height);
*/
export function sleep(milliseconds) {
return new Promise(resolve => {
- let id = GLib.timeout_add(GLib.PRIORITY_DEFAULT, milliseconds, () => {
+ const id = GLib.timeout_add(GLib.PRIORITY_DEFAULT, milliseconds, () => {
resolve();
return GLib.SOURCE_REMOVE;
});
/** @private */
export function _spawnPerfHelper() {
- let path = GLib.getenv('GNOME_SHELL_BUILDDIR') || Config.LIBEXECDIR;
- let command = `${path}/gnome-shell-perf-helper`;
+ const path = GLib.getenv('GNOME_SHELL_BUILDDIR') || Config.LIBEXECDIR;
+ const command = `${path}/gnome-shell-perf-helper`;
Util.trySpawnCommandLine(command);
}
textInput: false,
});
- let perfHelper = await _getPerfHelper();
+ const perfHelper = await _getPerfHelper();
perfHelper.CreateWindowAsync(
params.width, params.height,
params.alpha, params.maximized,
* created with createTestWindow have been mapped and exposed.
*/
export async function waitTestWindows() {
- let perfHelper = await _getPerfHelper();
+ const perfHelper = await _getPerfHelper();
return perfHelper.WaitWindowsAsync().catch(logError);
}
* process because of normal X asynchronicity.
*/
export async function destroyTestWindows() {
- let perfHelper = await _getPerfHelper();
+ const perfHelper = await _getPerfHelper();
return perfHelper.DestroyWindowsAsync().catch(logError);
}
* running until something else makes it exit, e.g. the Wayland socket closing.
*/
export async function disableHelperAutoExit() {
- let perfHelper = await _getPerfHelper();
+ const perfHelper = await _getPerfHelper();
perfHelper._autoExit = false;
}
}
function _collect(scriptModule, outputFile) {
- let eventHandlers = {};
+ const eventHandlers = {};
- for (let f in scriptModule) {
- let m = /([A-Za-z]+)_([A-Za-z]+)/.exec(f);
+ for (const f in scriptModule) {
+ const m = /([A-Za-z]+)_([A-Za-z]+)/.exec(f);
if (m)
eventHandlers[`${m[1]}.${m[2]}`] = scriptModule[f];
}
scriptModule.finish();
if (outputFile) {
- let f = Gio.file_new_for_path(outputFile);
- let raw = f.replace(null,
+ const f = Gio.file_new_for_path(outputFile);
+ const raw = f.replace(null,
false,
Gio.FileCreateFlags.NONE,
null);
- let out = Gio.BufferedOutputStream.new_sized(raw, 4096);
+ const out = Gio.BufferedOutputStream.new_sized(raw, 4096);
Shell.write_string_to_stream(out, '{\n');
Shell.write_string_to_stream(out, '"events":\n');
Shell.PerfLog.get_default().dump_events(out);
- let monitors = Main.layoutManager.monitors;
- let primary = Main.layoutManager.primaryIndex;
+ const monitors = Main.layoutManager.monitors;
+ const primary = Main.layoutManager.primaryIndex;
Shell.write_string_to_stream(out, ',\n"monitors":\n[');
for (let i = 0; i < monitors.length; i++) {
- let monitor = monitors[i];
+ const monitor = monitors[i];
if (i !== 0)
Shell.write_string_to_stream(out, ', ');
const prefix = i === primary ? '*' : '';
Shell.write_string_to_stream(out, ',\n"metrics":\n[ ');
let first = true;
- for (let name in scriptModule.METRICS) {
- let metric = scriptModule.METRICS[name];
+ for (const name in scriptModule.METRICS) {
+ const metric = scriptModule.METRICS[name];
// Extra checks here because JSON.stringify generates
// invalid JSON for undefined values
if (metric.description == null) {
Shell.write_string_to_stream(out, '\n}\n');
out.close(null);
} else {
- let metrics = [];
- for (let metric in scriptModule.METRICS)
+ const metrics = [];
+ for (const metric in scriptModule.METRICS)
metrics.push(metric);
metrics.sort();
print('------------------------------------------------------------');
for (let i = 0; i < metrics.length; i++) {
- let metric = metrics[i];
+ const metric = metrics[i];
print(`# ${scriptModule.METRICS[metric].description}`);
print(`${metric}: ${scriptModule.METRICS[metric].value}${scriptModule.METRICS[metric].units}`);
}
const MaxWidthBox = GObject.registerClass(
class MaxWidthBox extends St.BoxLayout {
vfunc_allocate(box) {
- let themeNode = this.get_theme_node();
- let maxWidth = themeNode.get_max_width();
- let availWidth = box.x2 - box.x1;
- let adjustedBox = box;
+ const themeNode = this.get_theme_node();
+ const maxWidth = themeNode.get_max_width();
+ const availWidth = box.x2 - box.x1;
+ const adjustedBox = box;
if (availWidth > maxWidth) {
- let excessWidth = availWidth - maxWidth;
+ const excessWidth = availWidth - maxWidth;
adjustedBox.x1 += Math.floor(excessWidth / 2);
adjustedBox.x2 -= Math.floor(excessWidth / 2);
}
this.style_class = 'list-search-result';
- let content = new St.BoxLayout({
+ const content = new St.BoxLayout({
style_class: 'list-search-result-content',
orientation: Clutter.Orientation.HORIZONTAL,
x_align: Clutter.ActorAlign.START,
});
this.set_child(content);
- let titleBox = new St.BoxLayout({
+ const titleBox = new St.BoxLayout({
style_class: 'list-search-result-title',
y_align: Clutter.ActorAlign.CENTER,
});
content.add_child(titleBox);
// An icon for, or thumbnail of, content
- let icon = this.metaInfo['createIcon'](this.ICON_SIZE);
+ const icon = this.metaInfo['createIcon'](this.ICON_SIZE);
if (icon)
titleBox.add_child(icon);
- let title = new St.Label({
+ const title = new St.Label({
text: this.metaInfo['name'],
y_align: Clutter.ActorAlign.CENTER,
});
}
_highlightTerms() {
- let markup = this._resultsView.highlightTerms(this.metaInfo['description'].split('\n')[0]);
+ const markup = this._resultsView.highlightTerms(this.metaInfo['description'].split('\n')[0]);
this._descriptionLabel.clutter_text.set_markup(markup);
}
});
this.icon = new IconGrid.BaseIcon(this.metaInfo['name'], {
createIcon: this.metaInfo['createIcon'],
});
- let content = new St.Bin({
+ const content = new St.Bin({
child: this.icon,
x_align: Clutter.ActorAlign.START,
x_expand: true,
this._resultDisplayBin = new St.Bin();
this.add_child(this._resultDisplayBin);
- let separator = new St.Widget({style_class: 'search-section-separator'});
+ const separator = new St.Widget({style_class: 'search-section-separator'});
this.add_child(separator);
this._resultDisplays = {};
clear() {
this._cancellable.cancel();
- for (let resultId in this._resultDisplays)
+ for (const resultId in this._resultDisplays)
this._resultDisplays[resultId].destroy();
this._resultDisplays = {};
this._clearResultDisplay();
}
async _ensureResultActors(results) {
- let metasNeeded = results.filter(
+ const metasNeeded = results.filter(
resultId => this._resultDisplays[resultId] === undefined);
if (metasNeeded.length === 0)
throw new Error(`Invalid result meta returned from search provider ${this.provider.id}`);
metasNeeded.forEach((resultId, i) => {
- let meta = metas[i];
- let display = this._createResultDisplay(meta);
+ const meta = metas[i];
+ const display = this._createResultDisplay(meta);
display.connect('key-focus-in', this._keyFocusIn.bind(this));
this._resultDisplays[resultId] = display;
});
this.hide();
callback();
} else {
- let maxResults = this._getMaxDisplayedResults();
- let results = maxResults > -1
+ const maxResults = this._getMaxDisplayedResults();
+ const results = maxResults > -1
? this.provider.filterResults(providerResults, maxResults)
: providerResults;
- let moreCount = Math.max(providerResults.length - results.length, 0);
+ const moreCount = Math.max(providerResults.length - results.length, 0);
try {
await this._ensureResultActors(results);
let natWidth = 0;
let first = true;
- for (let child of container) {
+ for (const child of container) {
if (!child.visible)
continue;
let minHeight = 0;
let natHeight = 0;
- for (let child of container) {
+ for (const child of container) {
if (!child.visible)
continue;
let accumulatedWidth = 0;
let first = true;
- for (let child of container) {
+ for (const child of container) {
if (!child.visible)
continue;
}
getFirstResult() {
- for (let child of this._grid) {
+ for (const child of this._grid) {
if (child.visible)
return child;
}
this._registerProvider(new AppDisplay.AppSearchProvider());
- let appSystem = Shell.AppSystem.get_default();
+ const appSystem = Shell.AppSystem.get_default();
appSystem.connect('installed-changed', this._reloadRemoteProviders.bind(this));
this._reloadRemoteProviders();
}
}
_reloadRemoteProviders() {
- let remoteProviders = this._providers.filter(p => p.isRemoteProvider);
+ const remoteProviders = this._providers.filter(p => p.isRemoteProvider);
remoteProviders.forEach(provider => {
this._unregisterProvider(provider);
});
}
_unregisterProvider(provider) {
- let index = this._providers.indexOf(provider);
+ const index = this._providers.indexOf(provider);
this._providers.splice(index, 1);
if (provider.display)
_doSearch() {
this._startingSearch = false;
- let previousResults = this._results;
+ const previousResults = this._results;
this._results = {};
this._providers.forEach(provider => {
- let previousProviderResults = previousResults[provider.id];
+ const previousProviderResults = previousResults[provider.id];
this._doProviderSearch(provider, previousProviderResults);
});
// setting state of the current search or cancelling the search.
// This will prevent incorrect state being as a result of a duplicate
// search while the previous search is still active.
- let searchString = terms.join(' ');
- let previousSearchString = this._terms.join(' ');
+ const searchString = terms.join(' ');
+ const previousSearchString = this._terms.join(' ');
if (searchString === previousSearchString)
return;
_maybeSetInitialSelection() {
let newDefaultResult = null;
- let providers = this._providers;
+ const providers = this._providers;
for (let i = 0; i < providers.length; i++) {
- let provider = providers[i];
- let display = provider.display;
+ const provider = providers[i];
+ const display = provider.display;
if (!display.visible)
continue;
- let firstResult = display.getFirstResult();
+ const firstResult = display.getFirstResult();
if (firstResult) {
newDefaultResult = firstResult;
break; // select this one!
}
_updateSearchProgress() {
- let haveResults = this._providers.some(provider => {
- let display = provider.display;
+ const haveResults = this._providers.some(provider => {
+ const display = provider.display;
return display.getFirstResult() != null;
});
}
_updateResults(provider, results) {
- let terms = this._terms;
- let display = provider.display;
+ const terms = this._terms;
+ const display = provider.display;
display.updateSearch(results, terms, () => {
provider.searchInProgress = false;
}
navigateFocus(direction) {
- let rtl = this.get_text_direction() === Clutter.TextDirection.RTL;
+ const rtl = this.get_text_direction() === Clutter.TextDirection.RTL;
if (direction === St.DirectionType.TAB_BACKWARD ||
direction === (rtl
? St.DirectionType.RIGHT
}
animateLaunch() {
- let appSys = Shell.AppSystem.get_default();
- let app = appSys.lookup_app(this.provider.appInfo.get_id());
+ const appSys = Shell.AppSystem.get_default();
+ const app = appSys.lookup_app(this.provider.appInfo.get_id());
if (app.state === Shell.AppState.STOPPED)
IconGrid.zoomOutActor(this._content);
}
if (Main.modalCount > 1)
return Clutter.EVENT_PROPAGATE;
- let symbol = event.get_key_symbol();
+ const symbol = event.get_key_symbol();
if (symbol === Clutter.KEY_Escape) {
if (this._searchActive)
if (symbol === Clutter.KEY_BackSpace && this._searchActive)
return true;
- let unicode = Clutter.keysym_to_unicode(symbol);
+ const unicode = Clutter.keysym_to_unicode(symbol);
if (unicode === 0)
return false;
}
_onTextChanged() {
- let terms = getTermsForSearchString(this._entry.get_text());
+ const terms = getTermsForSearchString(this._entry.get_text());
const searchActive = terms.length > 0;
this._searchResults.setTerms(terms);
}
_onKeyPress(entry, event) {
- let symbol = event.get_key_symbol();
+ const symbol = event.get_key_symbol();
if (symbol === Clutter.KEY_Escape) {
if (this._isActivated()) {
this.reset();
};
function _loadMode(file, info) {
- let name = info.get_name();
- let suffix = name.indexOf('.json');
- let modeName = suffix === -1 ? name : name.slice(name, suffix);
+ const name = info.get_name();
+ const suffix = name.indexOf('.json');
+ const modeName = suffix === -1 ? name : name.slice(name, suffix);
if (Object.prototype.hasOwnProperty.call(_modes, modeName))
return;
_modes[modeName] = {};
const excludedProps = ['unlockDialog'];
- for (let prop in _modes[DEFAULT_MODE]) {
+ for (const prop in _modes[DEFAULT_MODE]) {
if (newMode[prop] !== undefined &&
!excludedProps.includes(prop))
_modes[modeName][prop] = newMode[prop];
export function listModes() {
_loadModes();
- let loop = new GLib.MainLoop(null, false);
- let id = GLib.idle_add(GLib.PRIORITY_DEFAULT, () => {
- let names = Object.getOwnPropertyNames(_modes);
+ const loop = new GLib.MainLoop(null, false);
+ const id = GLib.idle_add(GLib.PRIORITY_DEFAULT, () => {
+ const names = Object.getOwnPropertyNames(_modes);
for (let i = 0; i < names.length; i++) {
if (_modes[names[i]].isPrimary)
print(names[i]);
super();
_loadModes();
- let isPrimary = _modes[global.session_mode] &&
+ const isPrimary = _modes[global.session_mode] &&
_modes[global.session_mode].isPrimary;
- let mode = isPrimary ? global.session_mode : 'user';
+ const mode = isPrimary ? global.session_mode : 'user';
this._modeStack = [mode];
this._sync();
}
// A simplified version of Lang.copyProperties, handles
// undefined as a special case for "no change / inherit from previous mode"
- for (let prop in params) {
+ for (const prop in params) {
if (params[prop] !== undefined)
this[prop] = params[prop];
}
return;
}
- for (let param in params)
+ for (const param in params)
params[param] = params[param].deepUnpack();
const {
return;
}
- let [accel, modeFlags, grabFlags] = params;
- let sender = invocation.get_sender();
- let bindingAction = this._grabAcceleratorForSender(accel, modeFlags, grabFlags, sender);
+ const [accel, modeFlags, grabFlags] = params;
+ const sender = invocation.get_sender();
+ const bindingAction = this._grabAcceleratorForSender(accel, modeFlags, grabFlags, sender);
invocation.return_value(GLib.Variant.new('(u)', [bindingAction]));
}
return;
}
- let [accels] = params;
- let sender = invocation.get_sender();
- let bindingActions = [];
+ const [accels] = params;
+ const sender = invocation.get_sender();
+ const bindingActions = [];
for (let i = 0; i < accels.length; i++) {
- let [accel, modeFlags, grabFlags] = accels[i];
+ const [accel, modeFlags, grabFlags] = accels[i];
bindingActions.push(this._grabAcceleratorForSender(accel, modeFlags, grabFlags, sender));
}
invocation.return_value(GLib.Variant.new('(au)', [bindingActions]));
return;
}
- let [action] = params;
- let sender = invocation.get_sender();
- let ungrabSucceeded = this._ungrabAcceleratorForSender(action, sender);
+ const [action] = params;
+ const sender = invocation.get_sender();
+ const ungrabSucceeded = this._ungrabAcceleratorForSender(action, sender);
invocation.return_value(GLib.Variant.new('(b)', [ungrabSucceeded]));
}
return;
}
- let [actions] = params;
- let sender = invocation.get_sender();
+ const [actions] = params;
+ const sender = invocation.get_sender();
let ungrabSucceeded = true;
for (let i = 0; i < actions.length; i++)
}
_emitAcceleratorSignal(signal, action, device, timestamp) {
- let destination = this._grabbedAccelerators.get(action);
+ const destination = this._grabbedAccelerators.get(action);
if (!destination)
return;
- let connection = this._dbusImpl.get_connection();
- let info = this._dbusImpl.get_info();
- let params = {
+ const connection = this._dbusImpl.get_connection();
+ const info = this._dbusImpl.get_info();
+ const params = {
'timestamp': GLib.Variant.new('u', timestamp),
'action-mode': GLib.Variant.new('u', Main.actionMode),
};
- let deviceNode = device.get_device_node();
+ const deviceNode = device.get_device_node();
if (deviceNode)
params['device-node'] = GLib.Variant.new('s', deviceNode);
}
_grabAcceleratorForSender(accelerator, modeFlags, grabFlags, sender) {
- let bindingAction = global.display.grab_accelerator(accelerator, grabFlags);
+ const bindingAction = global.display.grab_accelerator(accelerator, grabFlags);
if (bindingAction === Meta.KeyBindingAction.NONE)
return Meta.KeyBindingAction.NONE;
- let bindingName = Meta.external_binding_name_for_action(bindingAction);
+ const bindingName = Meta.external_binding_name_for_action(bindingAction);
Main.wm.allowKeybinding(bindingName, modeFlags);
this._grabbedAccelerators.set(bindingAction, sender);
if (!this._grabbers.has(sender)) {
- let id = Gio.bus_watch_name(Gio.BusType.SESSION,
+ const id = Gio.bus_watch_name(Gio.BusType.SESSION,
sender, 0, null, this._onGrabberBusNameVanished.bind(this));
this._grabbers.set(sender, id);
}
}
_ungrabAccelerator(action) {
- let ungrabSucceeded = global.display.ungrab_accelerator(action);
+ const ungrabSucceeded = global.display.ungrab_accelerator(action);
if (ungrabSucceeded)
this._grabbedAccelerators.delete(action);
}
_ungrabAcceleratorForSender(action, sender) {
- let grabbedBy = this._grabbedAccelerators.get(action);
+ const grabbedBy = this._grabbedAccelerators.get(action);
if (sender !== grabbedBy)
return false;
}
_onGrabberBusNameVanished(connection, name) {
- let grabs = this._grabbedAccelerators.entries();
- for (let [action, sender] of grabs) {
+ const grabs = this._grabbedAccelerators.entries();
+ for (const [action, sender] of grabs) {
if (sender === name)
this._ungrabAccelerator(action);
}
return;
}
- let sender = invocation.get_sender();
- let [dict] = params;
+ const sender = invocation.get_sender();
+ const [dict] = params;
Main.osdMonitorLabeler.show(sender, dict);
invocation.return_value(null);
}
return;
}
- let sender = invocation.get_sender();
+ const sender = invocation.get_sender();
Main.osdMonitorLabeler.hide(sender);
invocation.return_value(null);
}
}
ListExtensions() {
- let out = {};
+ const out = {};
Main.extensionManager.getUuids().forEach(uuid => {
- let dbusObj = this.GetExtensionInfo(uuid);
+ const dbusObj = this.GetExtensionInfo(uuid);
out[uuid] = dbusObj;
});
return out;
}
GetExtensionInfo(uuid) {
- let extension = Main.extensionManager.lookup(uuid) || {};
+ const extension = Main.extensionManager.lookup(uuid) || {};
return ExtensionUtils.serializeExtension(extension);
}
GetExtensionErrors(uuid) {
- let extension = Main.extensionManager.lookup(uuid);
+ const extension = Main.extensionManager.lookup(uuid);
if (!extension)
return [];
}
_extensionStateChanged(_, newState) {
- let state = ExtensionUtils.serializeExtension(newState);
+ const state = ExtensionUtils.serializeExtension(newState);
this._dbusImpl.emit_signal('ExtensionStateChanged',
new GLib.Variant('(sa{sv})', [newState.uuid, state]));
}
LockAsync(parameters, invocation) {
- let tmpId = this._screenShield.connect('lock-screen-shown', () => {
+ const tmpId = this._screenShield.connect('lock-screen-shown', () => {
this._screenShield.disconnect(tmpId);
invocation.return_value(null);
}
GetActiveTime() {
- let started = this._screenShield.activationTime;
+ const started = this._screenShield.activationTime;
if (started > 0)
return Math.floor((GLib.get_monotonic_time() - started) / 1000000);
else
}
_makePasswordItem() {
- let item = new PopupMenu.PopupMenuItem('');
+ const item = new PopupMenu.PopupMenuItem('');
item.connect('activate', this._onPasswordActivated.bind(this));
this.addMenuItem(item);
this._passwordItem = item;
super.open(animate);
this._entry.add_style_pseudo_class('focus');
- let direction = St.DirectionType.TAB_FORWARD;
+ const direction = St.DirectionType.TAB_FORWARD;
if (!this.actor.navigate_focus(null, direction, false))
this.actor.grab_key_focus();
}
_updateCopyItem() {
- let selection = this._entry.clutter_text.get_selection();
+ const selection = this._entry.clutter_text.get_selection();
this._copyItem.setSensitive(!this._entry.clutter_text.password_char &&
selection && selection !== '');
}
}
_onCopyActivated() {
- let selection = this._entry.clutter_text.get_selection();
+ const selection = this._entry.clutter_text.get_selection();
this._clipboard.set_text(St.ClipboardType.CLIPBOARD, selection);
}
if (!text)
return;
this._entry.clutter_text.delete_selection();
- let pos = this._entry.clutter_text.get_cursor_position();
+ const pos = this._entry.clutter_text.get_cursor_position();
this._entry.clutter_text.insert_text(text, pos);
});
}
}
function _setMenuAlignment(entry, stageX) {
- let [success, entryX] = entry.transform_stage_point(stageX, 0);
+ const [success, entryX] = entry.transform_stage_point(stageX, 0);
if (success)
entry.menu.setSourceAlignment(entryX / entry.width);
}
entry.menu.close(BoxPointer.PopupAnimation.FULL);
return Clutter.EVENT_STOP;
} else if (event.get_button() === 3) {
- let [stageX] = event.get_coords();
+ const [stageX] = event.get_coords();
_setMenuAlignment(entry, stageX);
entry.menu.open(BoxPointer.PopupAnimation.FULL);
return Clutter.EVENT_STOP;
}
function _onPopup(actor, entry) {
- let cursorPosition = entry.clutter_text.get_cursor_position();
- let [success, textX, textY_, lineHeight_] = entry.clutter_text.position_to_coords(cursorPosition);
+ const cursorPosition = entry.clutter_text.get_cursor_position();
+ const [success, textX, textY_, lineHeight_] = entry.clutter_text.position_to_coords(cursorPosition);
if (success)
entry.menu.setSourceAlignment(textX / entry.width);
entry.menu.open(BoxPointer.PopupAnimation.FULL);
}
_sync(animate) {
- let capsLockOn = this._keymap.get_caps_lock_state();
+ const capsLockOn = this._keymap.get_caps_lock_state();
this.remove_all_transitions();
const {naturalHeightSet} = this;
this.natural_height_set = false;
- let [, height] = this.get_preferred_height(-1);
+ const [, height] = this.get_preferred_height(-1);
this.natural_height_set = naturalHeightSet;
this.ease({
/* ------ Common Utils ------- */
function _setButtonsForChoices(dialog, oldChoices, choices) {
- let buttons = [];
+ const buttons = [];
let buttonsChanged = oldChoices.length !== choices.length;
for (let idx = 0; idx < choices.length; idx++) {
- let button = idx;
+ const button = idx;
buttonsChanged ||= oldChoices[idx] !== choices[idx];
}
function _setLabelsForMessage(content, message) {
- let labels = message.split('\n');
+ const labels = message.split('\n');
content.title = labels.shift();
content.description = labels.join('\n');
_onShowProcesses2(op) {
this._closeExistingDialog();
- let processes = op.get_show_processes_pids();
- let choices = op.get_show_processes_choices();
- let message = op.get_show_processes_message();
+ const processes = op.get_show_processes_pids();
+ const choices = op.get_show_processes_choices();
+ const message = op.get_show_processes_message();
if (!this._processesDialog) {
this._processesDialog = new ShellProcessesDialog();
},
}, class ShellMountPasswordDialog extends ModalDialog.ModalDialog {
_init(message, flags) {
- let strings = message.split('\n');
- let title = strings.shift() || null;
- let description = strings.shift() || null;
+ const strings = message.split('\n');
+ const title = strings.shift() || null;
+ const description = strings.shift() || null;
super._init({styleClass: 'prompt-dialog'});
- let disksApp = Shell.AppSystem.get_default().lookup_app('org.gnome.DiskUtility.desktop');
+ const disksApp = Shell.AppSystem.get_default().lookup_app('org.gnome.DiskUtility.desktop');
- let content = new Dialog.MessageDialogContent({title, description});
+ const content = new Dialog.MessageDialogContent({title, description});
- let passwordGridLayout = new Clutter.GridLayout({orientation: Clutter.Orientation.VERTICAL});
- let passwordGrid = new St.Widget({
+ const passwordGridLayout = new Clutter.GridLayout({orientation: Clutter.Orientation.VERTICAL});
+ const passwordGrid = new St.Widget({
style_class: 'prompt-dialog-password-grid',
layout_manager: passwordGridLayout,
});
passwordGridLayout.hookup_style(passwordGrid);
- let rtl = passwordGrid.get_text_direction() === Clutter.TextDirection.RTL;
+ const rtl = passwordGrid.get_text_direction() === Clutter.TextDirection.RTL;
let curGridRow = 0;
if (flags & Gio.AskPasswordFlags.TCRYPT) {
}
curGridRow += 1;
- let warningBox = new St.BoxLayout({orientation: Clutter.Orientation.VERTICAL});
+ const warningBox = new St.BoxLayout({orientation: Clutter.Orientation.VERTICAL});
- let capsLockWarning = new ShellEntry.CapsLockWarning();
+ const capsLockWarning = new ShellEntry.CapsLockWarning();
warningBox.add_child(capsLockWarning);
this._errorMessageLabel = new St.Label({
}
_onKeyfilesCheckboxClicked() {
- let useKeyfiles = this._keyfilesCheckbox.checked;
+ const useKeyfiles = this._keyfilesCheckbox.checked;
this._passwordEntry.reactive = !useKeyfiles;
this._passwordEntry.can_focus = !useKeyfiles;
this._pimEntry.reactive = !useKeyfiles;
this._applicationSection.list.destroy_all_children();
pids.forEach(pid => {
- let tracker = Shell.WindowTracker.get_default();
- let app = tracker.get_app_from_pid(pid);
+ const tracker = Shell.WindowTracker.get_default();
+ const app = tracker.get_app_from_pid(pid);
if (!app)
return;
- let listItem = new Dialog.ListSectionItem({
+ const listItem = new Dialog.ListSectionItem({
icon_actor: app.create_icon_texture(LIST_ITEM_ICON_SIZE),
title: app.get_name(),
});
}
_setCurrentRequest(invocation, id, type) {
- let oldId = this._currentId;
- let oldType = this._currentType;
- let requestId = `${id}@${invocation.get_sender()}`;
+ const oldId = this._currentId;
+ const oldType = this._currentType;
+ const requestId = `${id}@${invocation.get_sender()}`;
this._clearCurrentRequest(Gio.MountOperationResult.UNHANDLED, {});
* The ID must be unique in the context of the calling process.
*/
AskPasswordAsync(params, invocation) {
- let [id, message, iconName_, defaultUser_, defaultDomain_, flags] = params;
+ const [id, message, iconName_, defaultUser_, defaultDomain_, flags] = params;
if (this._setCurrentRequest(invocation, id, ShellMountOperationType.ASK_PASSWORD)) {
this._dialog.reaskPassword();
this._dialog = new ShellMountPasswordDialog(message, flags);
this._dialog.connect('response',
(object, choice, password, remember, hiddenVolume, systemVolume, pim) => {
- let details = {};
+ const details = {};
let response;
if (choice === -1) {
} else {
response = Gio.MountOperationResult.HANDLED;
- let passSave = remember ? Gio.PasswordSave.PERMANENTLY : Gio.PasswordSave.NEVER;
+ const passSave = remember ? Gio.PasswordSave.PERMANENTLY : Gio.PasswordSave.NEVER;
details['password_save'] = GLib.Variant.new('u', passSave);
details['password'] = GLib.Variant.new('s', password);
details['hidden_volume'] = GLib.Variant.new('b', hiddenVolume);
* @param {Gio.DBusMethodInvocation} invocation - invocation
*/
AskQuestionAsync(params, invocation) {
- let [id, message, iconName_, choices] = params;
+ const [id, message, iconName_, choices] = params;
if (this._setCurrentRequest(invocation, id, ShellMountOperationType.ASK_QUESTION)) {
this._dialog.update(message, choices);
this._dialog = new ShellMountQuestionDialog(message);
this._dialog.connect('response', (object, choice) => {
let response;
- let details = {};
+ const details = {};
if (choice === -1) {
response = Gio.MountOperationResult.ABORTED;
* @param {Gio.DBusMethodInvocation} invocation - invocation
*/
ShowProcessesAsync(params, invocation) {
- let [id, message, iconName_, applicationPids, choices] = params;
+ const [id, message, iconName_, applicationPids, choices] = params;
if (this._setCurrentRequest(invocation, id, ShellMountOperationType.SHOW_PROCESSES)) {
this._dialog.update(message, applicationPids, choices);
this._dialog = new ShellProcessesDialog();
this._dialog.connect('response', (object, choice) => {
let response;
- let details = {};
+ const details = {};
if (choice === -1) {
response = Gio.MountOperationResult.ABORTED;
super.vfunc_repaint();
// Add handle
- let cr = this.get_context();
- let themeNode = this.get_theme_node();
- let [width, height] = this.get_surface_size();
+ const cr = this.get_context();
+ const themeNode = this.get_theme_node();
+ const [width, height] = this.get_surface_size();
const rtl = this.get_text_direction() === Clutter.TextDirection.RTL;
const handleY = height / 2;
if (rtl)
handleX = width - handleX;
- let color = themeNode.get_foreground_color();
+ const color = themeNode.get_foreground_color();
cr.setSourceColor(color);
cr.arc(handleX, handleY, this._handleRadius, 0, 2 * Math.PI);
cr.fill();
// sure that no 'notify::value' signal is emitted before this one.
this.emit('drag-begin');
- let absX, absY;
- [absX, absY] = event.get_coords();
+ const [absX, absY] = event.get_coords();
this._moveHandle(absX, absY);
return Clutter.EVENT_STOP;
}
}
vfunc_scroll_event(event) {
- let direction = event.get_scroll_direction();
+ const direction = event.get_scroll_direction();
let nSteps = 0;
if (event.get_flags() & Clutter.EventFlags.FLAG_POINTER_EMULATED)
} else if (direction === Clutter.ScrollDirection.UP) {
nSteps = 1;
} else if (direction === Clutter.ScrollDirection.SMOOTH) {
- let [dx] = event.get_scroll_delta();
+ const [dx] = event.get_scroll_delta();
nSteps = dx;
// Match physical direction
if (event.get_scroll_flags() & Clutter.ScrollFlags.INVERTED)
}
_motionEvent(actor, event) {
- let absX, absY;
- [absX, absY] = event.get_coords();
+ const [absX, absY] = event.get_coords();
this._moveHandle(absX, absY);
return Clutter.EVENT_STOP;
}
vfunc_key_press_event(event) {
- let key = event.get_key_symbol();
+ const key = event.get_key_symbol();
if (key === Clutter.KEY_Right || key === Clutter.KEY_Left) {
const rtl = this.get_text_direction() === Clutter.TextDirection.RTL;
const increaseKey = rtl ? Clutter.KEY_Left : Clutter.KEY_Right;
}
_moveHandle(absX, _absY) {
- let relX, sliderX;
- [sliderX] = this.get_transformed_position();
+ let relX;
+ const [sliderX] = this.get_transformed_position();
const rtl = this.get_text_direction() === Clutter.TextDirection.RTL;
- let width = this._barLevelWidth;
+ const width = this._barLevelWidth;
relX = absX - sliderX;
if (rtl)
this._a11ySettings = new Gio.Settings({schema_id: A11Y_SCHEMA});
this._a11ySettings.connect(`changed::${KEY_ALWAYS_SHOW}`, this._queueSyncMenuVisibility.bind(this));
- let highContrast = this._buildItem(_('High Contrast'), A11Y_INTERFACE_SCHEMA, KEY_HIGH_CONTRAST);
+ const highContrast = this._buildItem(_('High Contrast'), A11Y_INTERFACE_SCHEMA, KEY_HIGH_CONTRAST);
this.menu.addMenuItem(highContrast);
const magnifier = this._buildItem(_('Zoom'),
APPLICATIONS_SCHEMA, 'screen-magnifier-enabled');
this.menu.addMenuItem(magnifier);
- let textZoom = this._buildFontItem();
+ const textZoom = this._buildFontItem();
this.menu.addMenuItem(textZoom);
const screenReader = this._buildItem(_('Screen Reader'),
_syncMenuVisibility() {
this._syncMenuVisibilityIdle = 0;
- let alwaysShow = this._a11ySettings.get_boolean(KEY_ALWAYS_SHOW);
- let items = this.menu._getMenuItems();
+ const alwaysShow = this._a11ySettings.get_boolean(KEY_ALWAYS_SHOW);
+ const items = this.menu._getMenuItems();
this.visible = alwaysShow || items.some(f => !!f.state);
settings.connect(`changed::${KEY_TEXT_SCALING_FACTOR}`, () => {
factor = settings.get_double(KEY_TEXT_SCALING_FACTOR);
- let active = factor > 1.0;
+ const active = factor > 1.0;
widget.block_signal_handler(toggledId);
widget.setToggleState(active);
}
_updateClickType(manager, clickType) {
- for (let mode in DWELL_CLICK_MODES) {
+ for (const mode in DWELL_CLICK_MODES) {
if (DWELL_CLICK_MODES[mode].type === clickType)
this._icon.icon_name = DWELL_CLICK_MODES[mode].icon;
}
}
_getXkbId() {
- let engineDesc = IBusManager.getIBusManager().getEngineDesc(this.id);
+ const engineDesc = IBusManager.getIBusManager().getEngineDesc(this.id);
if (!engineDesc)
return this.id;
});
box.add_child(symbol);
- let text = new St.Label({
+ const text = new St.Label({
text: item.displayName,
x_align: Clutter.ActorAlign.CENTER,
});
}
get inputSources() {
- let sourcesList = [];
- let layouts = this._layouts.split(',');
- let variants = this._variants.split(',');
+ const sourcesList = [];
+ const layouts = this._layouts.split(',');
+ const variants = this._variants.split(',');
for (let i = 0; i < layouts.length && !!layouts[i]; i++) {
let id = layouts[i];
}
_getSourcesList(key) {
- let sourcesList = [];
- let sources = this._settings.get_value(key);
- let nSources = sources.n_children();
+ const sourcesList = [];
+ const sources = this._settings.get_value(key);
+ const nSources = sources.n_children();
for (let i = 0; i < nSources; i++) {
- let [type, id] = sources.get_child_value(i).deepUnpack();
+ const [type, id] = sources.get_child_value(i).deepUnpack();
sourcesList.push({type, id});
}
return sourcesList;
}
set mruSources(sourcesList) {
- let sources = GLib.Variant.new('a(ss)', sourcesList);
+ const sources = GLib.Variant.new('a(ss)', sourcesList);
this._settings.set_value(this._KEY_MRU_SOURCES, sources);
}
}
_modifiersSwitcher() {
- let sourceIndexes = Object.keys(this._inputSources);
+ const sourceIndexes = Object.keys(this._inputSources);
if (sourceIndexes.length === 0) {
KeyboardManager.releaseKeyboard();
return true;
if (this._disableIBus)
return;
- let sourcesList = [];
+ const sourcesList = [];
for (let i = 0; i < this._mruSources.length; ++i) {
- let source = this._mruSources[i];
+ const source = this._mruSources[i];
sourcesList.push([source.type, source.id]);
}
for (let i = 1; i < this._mruSources.length; ++i) {
if (this._mruSources[i] === newSource) {
- let currentSource = this._mruSources.splice(i, 1);
+ const currentSource = this._mruSources.splice(i, 1);
this._mruSources = currentSource.concat(this._mruSources);
break;
}
}
_updateMruSources() {
- let sourcesList = [];
- for (let i of Object.keys(this._inputSources).sort((a, b) => a - b))
+ const sourcesList = [];
+ for (const i of Object.keys(this._inputSources).sort((a, b) => a - b))
sourcesList.push(this._inputSources[i]);
this._keyboardManager.setUserLayouts(sourcesList.map(x => x.xkbId));
// Initialize from settings when we have no MRU sources list
if (this._mruSources.length === 0) {
- let mruSettings = this._settings.mruSources;
+ const mruSettings = this._settings.mruSources;
for (let i = 0; i < mruSettings.length; i++) {
- let mruSettingSource = mruSettings[i];
+ const mruSettingSource = mruSettings[i];
let mruSource = null;
for (let j = 0; j < sourcesList.length; j++) {
- let source = sourcesList[j];
+ const source = sourcesList[j];
if (source.type === mruSettingSource.type &&
source.id === mruSettingSource.id) {
mruSource = source;
}
_inputSourcesChanged() {
- let sources = this._settings.inputSources;
- let nSources = sources.length;
+ const sources = this._settings.inputSources;
+ const nSources = sources.length;
this._currentSource = null;
this._inputSources = {};
this._ibusSources = {};
- let infosList = [];
+ const infosList = [];
for (let i = 0; i < nSources; i++) {
let displayName;
let shortName;
- let type = sources[i].type;
- let id = sources[i].id;
+ const type = sources[i].type;
+ const id = sources[i].id;
let exists = false;
if (type === INPUT_SOURCE_TYPE_XKB) {
} else if (type === INPUT_SOURCE_TYPE_IBUS) {
if (this._disableIBus)
continue;
- let engineDesc = this._ibusManager.getEngineDesc(id);
+ const engineDesc = this._ibusManager.getEngineDesc(id);
if (engineDesc) {
- let language = IBus.get_language_name(engineDesc.get_language());
+ const language = IBus.get_language_name(engineDesc.get_language());
let longName = engineDesc.get_longname();
- let textdomain = engineDesc.get_textdomain();
+ const textdomain = engineDesc.get_textdomain();
if (textdomain !== '')
longName = Gettext.dgettext(textdomain, longName);
exists = true;
}
if (infosList.length === 0) {
- let type = INPUT_SOURCE_TYPE_XKB;
- let id = KeyboardManager.DEFAULT_LAYOUT;
- let [, displayName, shortName] = this._xkbInfo.get_layout_info(id);
+ const type = INPUT_SOURCE_TYPE_XKB;
+ const id = KeyboardManager.DEFAULT_LAYOUT;
+ const [, displayName, shortName] = this._xkbInfo.get_layout_info(id);
infosList.push({type, id, displayName, shortName});
}
- let inputSourcesByShortName = {};
+ const inputSourcesByShortName = {};
for (let i = 0; i < infosList.length; i++) {
- let is = new InputSource(infosList[i].type,
+ const is = new InputSource(infosList[i].type,
infosList[i].id,
infosList[i].displayName,
infosList[i].shortName,
this._ibusSources[is.id] = is;
}
- for (let i in this._inputSources) {
- let is = this._inputSources[i];
+ for (const i in this._inputSources) {
+ const is = this._inputSources[i];
if (inputSourcesByShortName[is.shortName].length > 1) {
- let sub = inputSourcesByShortName[is.shortName].indexOf(is) + 1;
+ const sub = inputSourcesByShortName[is.shortName].indexOf(is) + 1;
is.shortName += String.fromCharCode(0x2080 + sub);
}
}
}
_makeEngineShortName(engineDesc) {
- let symbol = engineDesc.get_symbol();
+ const symbol = engineDesc.get_symbol();
if (symbol && symbol[0])
return symbol;
- let langCode = engineDesc.get_language().split('_', 1)[0];
+ const langCode = engineDesc.get_language().split('_', 1)[0];
if (langCode.length === 2 || langCode.length === 3)
return langCode.toLowerCase();
}
_ibusPropertiesRegistered(im, engineName, props) {
- let source = this._ibusSources[engineName];
+ const source = this._ibusSources[engineName];
if (!source)
return;
}
_ibusPropertyUpdated(im, engineName, prop) {
- let source = this._ibusSources[engineName];
+ const source = this._ibusSources[engineName];
if (!source)
return;
}
_getNewInputSource(current) {
- let sourceIndexes = Object.keys(this._inputSources);
+ const sourceIndexes = Object.keys(this._inputSources);
if (sourceIndexes.length === 0)
return null;
if (current) {
- for (let i in this._inputSources) {
- let is = this._inputSources[i];
+ for (const i in this._inputSources) {
+ const is = this._inputSources[i];
if (is.type === current.type &&
is.id === current.id)
return is;
}
_setPerWindowInputSource() {
- let window = this._getCurrentWindow();
+ const window = this._getCurrentWindow();
if (!window)
return;
this._focusWindowNotifyId = 0;
Main.overview.disconnectObject(this);
- let windows = global.get_window_actors().map(w => w.meta_window);
+ const windows = global.get_window_actors().map(w => w.meta_window);
for (let i = 0; i < windows.length; ++i) {
delete windows[i]._inputSources;
delete windows[i]._currentSource;
if (!this._sourcesPerWindow)
return;
- let window = this._getCurrentWindow();
+ const window = this._getCurrentWindow();
if (!window)
return;
// for the height of all children, but we ignore the results
// for those we don't actually display.
return this.get_children().reduce((maxWidth, child) => {
- let width = child.get_preferred_width(forHeight);
+ const width = child.get_preferred_width(forHeight);
return [
Math.max(maxWidth[0], width[0]),
Math.max(maxWidth[1], width[1]),
vfunc_get_preferred_height(forWidth) {
return this.get_children().reduce((maxHeight, child) => {
- let height = child.get_preferred_height(forWidth);
+ const height = child.get_preferred_height(forWidth);
return [
Math.max(maxHeight[0], height[0]),
Math.max(maxHeight[1], height[1]),
}
_sourcesChanged() {
- for (let i in this._menuItems)
+ for (const i in this._menuItems)
this._menuItems[i].destroy();
- for (let i in this._indicatorLabels)
+ for (const i in this._indicatorLabels)
this._indicatorLabels[i].destroy();
this._menuItems = {};
this._indicatorLabels = {};
let menuIndex = 0;
- for (let i in this._inputSourceManager.inputSources) {
- let is = this._inputSourceManager.inputSources[i];
+ for (const i in this._inputSourceManager.inputSources) {
+ const is = this._inputSourceManager.inputSources[i];
- let menuItem = new LayoutMenuItem(is.displayName, is.shortName);
+ const menuItem = new LayoutMenuItem(is.displayName, is.shortName);
menuItem.connect('activate', () => is.activate(true));
const indicatorLabel = new St.Label({
}
_currentSourceChanged(manager, oldSource) {
- let nVisibleSources = Object.keys(this._inputSourceManager.inputSources).length;
- let newSource = this._inputSourceManager.currentSource;
+ const nVisibleSources = Object.keys(this._inputSourceManager.inputSources).length;
+ const newSource = this._inputSourceManager.currentSource;
if (oldSource) {
this._menuItems[oldSource.index].setOrnament(PopupMenu.Ornament.NO_DOT);
if (!props)
return;
- let ibusManager = IBusManager.getIBusManager();
- let radioGroup = [];
+ const ibusManager = IBusManager.getIBusManager();
+ const radioGroup = [];
let p;
for (let i = 0; (p = props.get(i)) != null; ++i) {
- let prop = p;
+ const prop = p;
if (!prop.get_visible())
continue;
else
text = prop.get_label().get_text();
- let currentSource = this._inputSourceManager.currentSource;
+ const currentSource = this._inputSourceManager.currentSource;
if (currentSource) {
- let indicatorLabel = this._indicatorLabels[currentSource.index];
+ const indicatorLabel = this._indicatorLabels[currentSource.index];
const graphemeClusters = this._getGraphemeClusters(text);
if (graphemeClusters.length > 0 && graphemeClusters.length < 3)
indicatorLabel.set_text(text);
}
let item;
- let type = prop.get_prop_type();
+ const type = prop.get_prop_type();
switch (type) {
case IBus.PropType.MENU:
item = new PopupMenu.PopupSubMenuMenuItem(prop.get_label().get_text());
if (item.prop.get_state() === IBus.PropState.CHECKED)
return;
- let group = item.radioGroup;
+ const group = item.radioGroup;
for (let j = 0; j < group.length; ++j) {
if (group[j] === item) {
item.setOrnament(PopupMenu.Ornament.DOT);
};
function accuracyLevelToString(accuracyLevel) {
- for (let key in GeoclueAccuracyLevel) {
+ for (const key in GeoclueAccuracyLevel) {
if (GeoclueAccuracyLevel[key] === accuracyLevel)
return key;
}
get maxAccuracyLevel() {
if (this.enabled) {
- let level = this._settings.get_string(MAX_ACCURACY_LEVEL);
+ const level = this._settings.get_string(MAX_ACCURACY_LEVEL);
return GeoclueAccuracyLevel[level.toUpperCase()] ||
GeoclueAccuracyLevel.NONE;
}
async AuthorizeAppAsync(params, invocation) {
- let [desktopId, reqAccuracyLevel] = params;
+ const [desktopId, reqAccuracyLevel] = params;
- let authorizer = new AppAuthorizer(desktopId,
+ const authorizer = new AppAuthorizer(desktopId,
reqAccuracyLevel, this._permStoreProxy, this.maxAccuracyLevel);
const accuracyLevel = await authorizer.authorize();
}
_notifyMaxAccuracyLevel() {
- let variant = new GLib.Variant('u', this.maxAccuracyLevel);
+ const variant = new GLib.Variant('u', this.maxAccuracyLevel);
this._agent.emit_property_changed('MaxAccuracyLevel', variant);
}
}
async authorize() {
- let appSystem = Shell.AppSystem.get_default();
+ const appSystem = Shell.AppSystem.get_default();
this._app = appSystem.lookup_app(`${this.desktopId}.desktop`);
if (this._app == null || this._permStoreProxy == null)
return this._completeAuth();
}
}
- let permission = this._permissions[this.desktopId];
+ const permission = this._permissions[this.desktopId];
if (permission == null) {
await this._userAuthorizeApp();
} else {
- let [levelStr] = permission || ['NONE'];
+ const [levelStr] = permission || ['NONE'];
this._accuracyLevel = GeoclueAccuracyLevel[levelStr] ||
GeoclueAccuracyLevel.NONE;
}
}
_userAuthorizeApp() {
- let name = this._app.get_name();
- let appInfo = this._app.get_app_info();
- let reason = appInfo.get_locale_string('X-Geoclue-Reason');
+ const name = this._app.get_name();
+ const appInfo = this._app.get_app_info();
+ const reason = appInfo.get_locale_string('X-Geoclue-Reason');
this._dialog =
new GeolocationDialog(name, reason, this.reqAccuracyLevel);
if (this._permStoreProxy == null)
return;
- let levelStr = accuracyLevelToString(this._accuracyLevel);
- let dateStr = Math.round(Date.now() / 1000).toString();
+ const levelStr = accuracyLevelToString(this._accuracyLevel);
+ const dateStr = Math.round(Date.now() / 1000).toString();
this._permissions[this.desktopId] = [levelStr, dateStr];
- let data = GLib.Variant.new('av', {});
+ const data = GLib.Variant.new('av', {});
try {
await this._permStoreProxy.SetAsync(
super._init({styleClass: 'geolocation-dialog'});
this.reqAccuracyLevel = reqAccuracyLevel;
- let content = new Dialog.MessageDialogContent({
+ const content = new Dialog.MessageDialogContent({
title: _('Allow location access'),
/* Translators: %s is an application name */
description: _('The app %s wants to access your location').format(name),
});
- let reasonLabel = new St.Label({
+ const reasonLabel = new St.Label({
text: reason,
style_class: 'message-dialog-description',
});
content.add_child(reasonLabel);
- let infoLabel = new St.Label({
+ const infoLabel = new St.Label({
text: _('Location access can be changed at any time from the privacy settings'),
style_class: 'message-dialog-description',
});
}
_autoConnect() {
- let connection = new NM.SimpleConnection();
+ const connection = new NM.SimpleConnection();
this._client.add_and_activate_connection_async(connection, this._device, null, null, null);
}
this._mobileDevice = null;
- let capabilities = device.current_capabilities;
+ const capabilities = device.current_capabilities;
if (device.udi.indexOf('/org/freedesktop/ModemManager1/Modem') === 0)
this._mobileDevice = new ModemManager.BroadbandModem(device.udi, capabilities);
else if (capabilities & NM.DeviceModemCapabilities.GSM_UMTS)
_updateAccessibleName() {
const secureString = this._network.secure ? _('Secure') : _('Not secure');
- let signalStrengthString = _('Signal strength %s%%').format(this._network.signal_strength);
+ const signalStrengthString = _('Signal strength %s%%').format(this._network.signal_strength);
// translators: The first placeholder is the network name, the second and indication whether it is secure, and the last the signal strength indication
this.accessible_name = _('%s, %s, %s').format(this._label.text, secureString, signalStrengthString);
}
if (!connection)
return false;
- let ip4config = connection.get_setting_ip4_config();
+ const ip4config = connection.get_setting_ip4_config();
if (!ip4config)
return false;
_init() {
super._init();
- let controller = global.backend.get_remote_access_controller();
+ const controller = global.backend.get_remote_access_controller();
if (!controller)
return;
else
chargingState = '';
- let fillLevel = 10 * Math.floor(this._proxy.Percentage / 10);
+ const fillLevel = 10 * Math.floor(this._proxy.Percentage / 10);
const charged =
this._proxy.State === UPower.DeviceState.FULLY_CHARGED ||
(this._proxy.State === UPower.DeviceState.CHARGING && fillLevel === 100);
}
async _getProxy() {
- let nodeInfo = Gio.DBusNodeInfo.new_for_xml(BoltClientInterface);
+ const nodeInfo = Gio.DBusNodeInfo.new_for_xml(BoltClientInterface);
try {
this._proxy = await Gio.DBusProxy.new(
Gio.DBus.system,
}
_onDeviceAdded(proxy, emitter, params) {
- let [path] = params;
- let device = new BoltDeviceProxy(Gio.DBus.system, BOLT_DBUS_NAME, path);
+ const [path] = params;
+ const device = new BoltDeviceProxy(Gio.DBus.system, BOLT_DBUS_NAME, path);
this.emit('device-added', device);
}
return;
/* check if we should enroll the device */
- let res = [false];
+ const res = [false];
this.emit('enroll-device', dev, res);
if (res[0] !== true)
return;
}
async _enrollDevicesIdle() {
- let devices = this._devicesToEnroll;
+ const devices = this._devicesToEnroll;
- let dev = devices.shift();
+ const dev = devices.shift();
if (dev === undefined)
return GLib.SOURCE_REMOVE;
/* Session callbacks */
_sync() {
- let active = !Main.sessionMode.isLocked && !Main.sessionMode.isGreeter;
+ const active = !Main.sessionMode.isLocked && !Main.sessionMode.isGreeter;
this._indicator.visible = active && this._client.probing;
}
/* AuthRobot callbacks */
_onEnrollDevice(obj, device, policy) {
/* only authorize new devices when in an unlocked user session */
- let unlocked = !Main.sessionMode.isLocked && !Main.sessionMode.isGreeter;
+ const unlocked = !Main.sessionMode.isLocked && !Main.sessionMode.isGreeter;
/* and if we have the permission to do so, otherwise we trigger a PolKit dialog */
- let allowed = this._perm && this._perm.allowed;
+ const allowed = this._perm && this._perm.allowed;
- let auth = unlocked && allowed;
+ const auth = unlocked && allowed;
policy[0] = auth;
log(`thunderbolt: [${device.Name}] auto enrollment: ${auth ? 'yes' : 'no'} (allowed: ${allowed ? 'yes' : 'no'})`);
if (!this._stream)
return;
- let value = this.slider.value;
- let volume = value * this._control.get_vol_max_norm();
- let prevMuted = this._stream.is_muted;
- let prevVolume = this._stream.volume;
+ const value = this.slider.value;
+ const volume = value * this._control.get_vol_max_norm();
+ const prevMuted = this._stream.is_muted;
+ const prevVolume = this._stream.volume;
if (volume < 1) {
this._stream.volume = 0;
if (!prevMuted)
}
this._stream.push_volume();
- let volumeChanged = this._stream.volume !== prevVolume;
+ const volumeChanged = this._stream.volume !== prevVolume;
if (volumeChanged && !this._notifyVolumeChangeId && !this._inDrag) {
this._notifyVolumeChangeId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 30, () => {
this._notifyVolumeChange();
return; // feedback not necessary while playing
this._volumeCancellable = new Gio.Cancellable();
- let player = global.display.get_sound_player();
+ const player = global.display.get_sound_player();
player.play_from_theme('audio-volume-change',
_('Volume changed'), this._volumeCancellable);
}
}
_updateVolume() {
- let muted = this._stream.is_muted;
+ const muted = this._stream.is_muted;
this._changeSlider(muted
? 0 : this._stream.volume / this._control.get_vol_max_norm());
this.iconLabel = muted ? _('Unmute') : _('Mute');
if (!this._stream)
return null;
- let volume = this._stream.volume;
+ const volume = this._stream.volume;
let n;
if (this._stream.is_muted || volume <= 0) {
n = 0;
if (this._stream) {
// skip gnome-volume-control and pavucontrol which appear
// as recording because they show the input level
- let skippedApps = [
+ const skippedApps = [
'org.gnome.VolumeControl',
'org.PulseAudio.pavucontrol',
];
}
});
-let VolumeIndicator = GObject.registerClass(
+const VolumeIndicator = GObject.registerClass(
class VolumeIndicator extends SystemIndicator {
constructor() {
super();
if (event.get_flags() & Clutter.EventFlags.FLAG_POINTER_EMULATED)
return Clutter.EVENT_PROPAGATE;
- let direction = event.get_scroll_direction();
+ const direction = event.get_scroll_direction();
let nSteps = 0;
if (direction === Clutter.ScrollDirection.DOWN) {
nSteps = -1;
} else if (direction === Clutter.ScrollDirection.UP) {
nSteps = 1;
} else if (direction === Clutter.ScrollDirection.SMOOTH) {
- let [, dy] = event.get_scroll_delta();
+ const [, dy] = event.get_scroll_delta();
nSteps = -dy;
// Match physical direction
if (event.get_scroll_flags() & Clutter.ScrollFlags.INVERTED)
if (this._state === TouchpadState.IGNORED)
return Clutter.EVENT_PROPAGATE;
- let time = event.get_time();
+ const time = event.get_time();
const [x, y] = event.get_coords();
const [dx, dy] = event.get_gesture_motion_delta_unaccelerated();
const vertical = this.orientation === Clutter.Orientation.VERTICAL;
const distance = vertical ? TOUCHPAD_BASE_HEIGHT : TOUCHPAD_BASE_WIDTH;
- let time = event.get_time();
- let [dx, dy] = event.get_scroll_delta();
+ const time = event.get_time();
+ const [dx, dy] = event.get_scroll_delta();
if (dx === 0 && dy === 0) {
this.emit('end', time, distance);
this._began = false;
}
if (!this._began) {
- let [x, y] = event.get_coords();
+ const [x, y] = event.get_coords();
this.emit('begin', time, x, y);
this._began = true;
}
return;
const rect = new Mtk.Rectangle({x, y, width: 1, height: 1});
- let monitor = global.display.get_monitor_index_for_rect(rect);
+ const monitor = global.display.get_monitor_index_for_rect(rect);
this.emit('begin', monitor);
}
export const SwitchMonitorPopup = GObject.registerClass(
class SwitchMonitorPopup extends SwitcherPopup.SwitcherPopup {
_init() {
- let items = [];
+ const items = [];
items.push({
icon: 'shell-display-mirror-symbolic',
}
_initialSelection() {
- let currentConfig = global.backend.get_monitor_manager().get_switch_config();
- let selectConfig = (currentConfig + 1) % this._items.length;
+ const currentConfig = global.backend.get_monitor_manager().get_switch_config();
+ const selectConfig = (currentConfig + 1) % this._items.length;
this._select(selectConfig);
}
});
box.add_child(icon);
- let text = new St.Label({
+ const text = new St.Label({
text: item.label,
x_align: Clutter.ActorAlign.CENTER,
});
vfunc_allocate(box) {
this.set_allocation(box);
- let childBox = new Clutter.ActorBox();
- let primary = Main.layoutManager.primaryMonitor;
+ const childBox = new Clutter.ActorBox();
+ const primary = Main.layoutManager.primaryMonitor;
- let leftPadding = this.get_theme_node().get_padding(St.Side.LEFT);
- let rightPadding = this.get_theme_node().get_padding(St.Side.RIGHT);
- let hPadding = leftPadding + rightPadding;
+ const leftPadding = this.get_theme_node().get_padding(St.Side.LEFT);
+ const rightPadding = this.get_theme_node().get_padding(St.Side.RIGHT);
+ const hPadding = leftPadding + rightPadding;
// Allocate the switcherList
// We select a size based on an icon size that does not overflow the screen
- let [, childNaturalHeight] = this._switcherList.get_preferred_height(primary.width - hPadding);
- let [, childNaturalWidth] = this._switcherList.get_preferred_width(childNaturalHeight);
+ const [, childNaturalHeight] = this._switcherList.get_preferred_height(primary.width - hPadding);
+ const [, childNaturalWidth] = this._switcherList.get_preferred_width(childNaturalHeight);
childBox.x1 = Math.max(primary.x + leftPadding, primary.x + Math.floor((primary.width - childNaturalWidth) / 2));
childBox.x2 = Math.min(primary.x + primary.width - rightPadding, childBox.x1 + childNaturalWidth);
childBox.y1 = primary.y + Math.floor((primary.height - childNaturalHeight) / 2);
if (this._items.length === 0)
return false;
- let grab = Main.pushModal(this);
+ const grab = Main.pushModal(this);
// We expect at least a keyboard grab here
if ((grab.get_seat_state() & Clutter.GrabState.KEYBOARD) === 0) {
Main.popModal(grab);
// details.) So we check now. (Have to do this after updating
// selection.)
if (this._modifierMask) {
- let [x_, y_, mods] = global.get_pointer();
+ const [x_, y_, mods] = global.get_pointer();
if (!(mods & this._modifierMask)) {
this._finish(global.get_current_time());
return true;
}
vfunc_key_press_event(event) {
- let keysym = event.get_key_symbol();
- let action = global.display.get_keybinding_action(
+ const keysym = event.get_key_symbol();
+ const action = global.display.get_keybinding_action(
event.get_key_code(), event.get_state());
this._disableHover();
vfunc_key_release_event(event) {
if (this._modifierMask) {
- let [x_, y_, mods] = global.get_pointer();
- let state = mods & this._modifierMask;
+ const [x_, y_, mods] = global.get_pointer();
+ const state = mods & this._modifierMask;
if (state === 0)
this._finish(event.get_time());
y_expand: true,
});
- let layoutManager = this._list.get_layout_manager();
+ const layoutManager = this._list.get_layout_manager();
this._list.spacing = 0;
this._list.connect('style-changed', () => {
}
addItem(item, label) {
- let bbox = new SwitcherButton(this._squareItems);
+ const bbox = new SwitcherButton(this._squareItems);
bbox.set_child(item);
this._list.add_child(bbox);
}
removeItem(index) {
- let item = this._items.splice(index, 1);
+ const item = this._items.splice(index, 1);
item[0].destroy();
this.emit('item-removed', index);
}
this._highlighted = index;
const adjustment = this._scrollView.hadjustment;
- let [value] = adjustment.get_values();
- let [absItemX] = this._items[index].get_transformed_position();
- let [result_, posX, posY_] = this.transform_stage_point(absItemX, 0);
- let [containerWidth] = this.get_transformed_size();
+ const [value] = adjustment.get_values();
+ const [absItemX] = this._items[index].get_transformed_position();
+ const [result_, posX, posY_] = this.transform_stage_point(absItemX, 0);
+ const [containerWidth] = this.get_transformed_size();
if (posX + this._items[index].get_width() > containerWidth)
this._scrollToRight(index);
else if (this._items[index].allocation.x1 - value < 0)
const adjustment = this._scrollView.hadjustment;
let [value, lower_, upper, stepIncrement_, pageIncrement_, pageSize] = adjustment.get_values();
- let item = this._items[index];
+ const item = this._items[index];
if (item.allocation.x1 < value)
value = Math.max(0, item.allocation.x1);
const adjustment = this._scrollView.hadjustment;
let [value, lower_, upper, stepIncrement_, pageIncrement_, pageSize] = adjustment.get_values();
- let item = this._items[index];
+ const item = this._items[index];
if (item.allocation.x1 < value)
value = Math.max(0, item.allocation.x1);
}
vfunc_get_preferred_width(forHeight) {
- let themeNode = this.get_theme_node();
- let [maxChildMin] = this._maxChildWidth(forHeight);
- let [minListWidth] = this._list.get_preferred_width(forHeight);
+ const themeNode = this.get_theme_node();
+ const [maxChildMin] = this._maxChildWidth(forHeight);
+ const [minListWidth] = this._list.get_preferred_width(forHeight);
return themeNode.adjust_preferred_width(maxChildMin, minListWidth);
}
let maxChildNat = 0;
for (let i = 0; i < this._items.length; i++) {
- let [childMin, childNat] = this._items[i].get_preferred_height(-1);
+ const [childMin, childNat] = this._items[i].get_preferred_height(-1);
maxChildMin = Math.max(childMin, maxChildMin);
maxChildNat = Math.max(childNat, maxChildNat);
}
if (this._squareItems) {
- let [childMin] = this._maxChildWidth(-1);
+ const [childMin] = this._maxChildWidth(-1);
maxChildMin = Math.max(childMin, maxChildMin);
maxChildNat = maxChildMin;
}
- let themeNode = this.get_theme_node();
+ const themeNode = this.get_theme_node();
return themeNode.adjust_preferred_height(maxChildMin, maxChildNat);
}
vfunc_allocate(box) {
this.set_allocation(box);
- let contentBox = this.get_theme_node().get_content_box(box);
- let width = contentBox.x2 - contentBox.x1;
- let height = contentBox.y2 - contentBox.y1;
+ const contentBox = this.get_theme_node().get_content_box(box);
+ const width = contentBox.x2 - contentBox.x1;
+ const height = contentBox.y2 - contentBox.y1;
- let leftPadding = this.get_theme_node().get_padding(St.Side.LEFT);
- let rightPadding = this.get_theme_node().get_padding(St.Side.RIGHT);
+ const leftPadding = this.get_theme_node().get_padding(St.Side.LEFT);
+ const rightPadding = this.get_theme_node().get_padding(St.Side.RIGHT);
- let [minListWidth] = this._list.get_preferred_width(height);
+ const [minListWidth] = this._list.get_preferred_width(height);
- let childBox = new Clutter.ActorBox();
- let scrollable = minListWidth > width;
+ const childBox = new Clutter.ActorBox();
+ const scrollable = minListWidth > width;
this._scrollView.allocate(contentBox);
* @param {St.Side} side
*/
export function drawArrow(area, side) {
- let themeNode = area.get_theme_node();
- let borderColor = themeNode.get_border_color(side);
- let bodyColor = themeNode.get_foreground_color();
+ const themeNode = area.get_theme_node();
+ const borderColor = themeNode.get_border_color(side);
+ const bodyColor = themeNode.get_foreground_color();
- let [width, height] = area.get_surface_size();
- let cr = area.get_context();
+ const [width, height] = area.get_surface_size();
+ const cr = area.get_context();
cr.setLineWidth(1.0);
cr.setSourceColor(borderColor);
}
_onDestroy() {
- let items = this._sources.entries();
- for (let [source, obj] of items)
+ const items = this._sources.entries();
+ for (const [source, obj] of items)
this._removeSource(source, obj);
for (const player of this._players.keys())
}
_makeNotificationSource(source, box) {
- let iconActor = new St.Icon({
+ const iconActor = new St.Icon({
style_class: 'unlock-dialog-notification-icon',
fallback_icon_name: 'application-x-executable',
});
source.bind_property('icon', iconActor, 'gicon', GObject.BindingFlags.SYNC_CREATE);
box.add_child(iconActor);
- let textBox = new St.BoxLayout({
+ const textBox = new St.BoxLayout({
x_expand: true,
y_expand: true,
y_align: Clutter.ActorAlign.CENTER,
});
box.add_child(textBox);
- let title = new St.Label({
+ const title = new St.Label({
style_class: 'unlock-dialog-notification-label',
x_expand: true,
x_align: Clutter.ActorAlign.START,
GObject.BindingFlags.SYNC_CREATE);
textBox.add_child(title);
- let count = source.unseenCount;
- let countLabel = new St.Label({
+ const count = source.unseenCount;
+ const countLabel = new St.Label({
text: `${count}`,
visible: count > 1,
style_class: 'unlock-dialog-notification-count-text',
}
_makeNotificationDetailedSource(source, box) {
- let iconActor = new St.Icon({
+ const iconActor = new St.Icon({
style_class: 'unlock-dialog-notification-icon',
fallback_icon_name: 'application-x-executable',
});
});
box.add_child(textBox);
- let title = new St.Label({
+ const title = new St.Label({
style_class: 'unlock-dialog-notification-label',
});
source.bind_property_full('title',
let visible = false;
for (let i = 0; i < source.notifications.length; i++) {
- let n = source.notifications[i];
+ const n = source.notifications[i];
if (n.acknowledged)
continue;
: GLib.markup_escape_text(bodyText, -1);
}
- let label = new St.Label({style_class: 'unlock-dialog-notification-count-text'});
+ const label = new St.Label({style_class: 'unlock-dialog-notification-count-text'});
label.clutter_text.set_markup(`<b>${n.title}</b> ${body}`);
textBox.add_child(label);
}
_updateSourceBoxStyle(source, obj, box) {
- let hasCriticalNotification =
+ const hasCriticalNotification =
source.notifications.some(n => n.urgency === MessageTray.Urgency.CRITICAL);
if (hasCriticalNotification !== obj.hasCriticalNotification) {
}
_sourceAdded(tray, source, initial) {
- let obj = {
+ const obj = {
visible: source.policy.showInLockScreen,
detailed: this._shouldShowDetails(source),
sourceBox: null,
if (!initial) {
// block scrollbars while animating, if they're not needed now
- let boxHeight = this._notificationBox.height;
+ const boxHeight = this._notificationBox.height;
if (this._scrollView.height >= boxHeight)
this._scrollView.vscrollbar_policy = St.PolicyType.NEVER;
- let widget = obj.sourceBox;
- let [, natHeight] = widget.get_preferred_height(-1);
+ const widget = obj.sourceBox;
+ const [, natHeight] = widget.get_preferred_height(-1);
widget.height = 0;
widget.ease({
height: natHeight,
_countChanged(source, obj) {
// A change in the number of notifications may change whether we show
// details.
- let newDetailed = this._shouldShowDetails(source);
- let oldDetailed = obj.detailed;
+ const newDetailed = this._shouldShowDetails(source);
+ const oldDetailed = obj.detailed;
obj.detailed = newDetailed;
obj.titleLabel = obj.countLabel = null;
this._showSource(source, obj, obj.sourceBox);
} else {
- let count = source.unseenCount;
+ const count = source.unseenCount;
obj.countLabel.text = `${count}`;
obj.countLabel.visible = count > 1;
}
}
_detailedChanged(source, obj) {
- let newDetailed = this._shouldShowDetails(source);
+ const newDetailed = this._shouldShowDetails(source);
if (obj.detailed === newDetailed)
return;
_updateClock() {
this._time.text = this._wallClock.clock.trim();
- let date = new Date();
+ const date = new Date();
/* Translators: This is a time format for a date in
long format */
- let dateFormat = Shell.util_translate_time_string(N_('%A %B %-d'));
+ const dateFormat = Shell.util_translate_time_string(N_('%A %B %-d'));
this._date.text = formatDateWithCFormatString(date, dateFormat);
}
}
vfunc_allocate(container, box) {
- let [width, height] = box.get_size();
+ const [width, height] = box.get_size();
- let tenthOfHeight = height / 10.0;
- let thirdOfHeight = height / 3.0;
+ const tenthOfHeight = height / 10.0;
+ const thirdOfHeight = height / 3.0;
- let [, , stackWidth, stackHeight] =
+ const [, , stackWidth, stackHeight] =
this._stack.get_preferred_size();
- let [, , notificationsWidth, notificationsHeight] =
+ const [, , notificationsWidth, notificationsHeight] =
this._notifications.get_preferred_size();
- let columnWidth = Math.max(stackWidth, notificationsWidth);
+ const columnWidth = Math.max(stackWidth, notificationsWidth);
- let columnX1 = Math.floor((width - columnWidth) / 2.0);
- let actorBox = new Clutter.ActorBox();
+ const columnX1 = Math.floor((width - columnWidth) / 2.0);
+ const actorBox = new Clutter.ActorBox();
// Notifications
- let maxNotificationsHeight = Math.min(
+ const maxNotificationsHeight = Math.min(
notificationsHeight,
height - tenthOfHeight - stackHeight);
this._notifications.allocate(actorBox);
// Authentication Box
- let stackY = Math.min(
+ const stackY = Math.min(
thirdOfHeight,
height - stackHeight - maxNotificationsHeight);
// Switch User button
if (this._switchUserButton.visible) {
- let [, , natWidth, natHeight] =
+ const [, , natWidth, natHeight] =
this._switchUserButton.get_preferred_size();
const textDirection = this._switchUserButton.get_text_direction();
if (this._swipeTracker.canHandleScrollEvent(event))
return Clutter.EVENT_PROPAGATE;
- let direction = event.get_scroll_direction();
+ const direction = event.get_scroll_direction();
if (direction === Clutter.ScrollDirection.UP)
this._showClock();
else if (direction === Clutter.ScrollDirection.DOWN)
this._updateUserSwitchVisibility();
// Main Box
- let mainBox = new St.Widget();
+ const mainBox = new St.Widget();
mainBox.add_constraint(new Layout.MonitorConstraint({primary: true}));
mainBox.add_child(this._stack);
mainBox.add_child(this._notificationsBox);
keyval === Clutter.KEY_Caps_Lock)
return Clutter.EVENT_PROPAGATE;
- let unichar = event.get_key_unicode();
+ const unichar = event.get_key_unicode();
this._showPrompt();
}
_createBackground(monitorIndex) {
- let monitor = Main.layoutManager.monitors[monitorIndex];
- let widget = new St.Widget({
+ const monitor = Main.layoutManager.monitors[monitorIndex];
+ const widget = new St.Widget({
style_class: 'screen-shield-background',
x: monitor.x,
y: monitor.y,
effect: new Shell.BlurEffect({name: 'blur'}),
});
- let bgManager = new Background.BackgroundManager({
+ const bgManager = new Background.BackgroundManager({
container: widget,
monitorIndex,
controlPosition: false,
}
_maybeDestroyAuthPrompt() {
- let focus = global.stage.key_focus;
+ const focus = global.stage.key_focus;
if (focus === null ||
(this._authPrompt && this._authPrompt.contains(focus)) ||
(this._otherUserButton && focus === this._otherUserButton))
this._ensureAuthPrompt();
- let progress = this._adjustment.value;
+ const progress = this._adjustment.value;
tracker.confirmSwipe(this._stack.height,
[0, 1],
progress,
export const Avatar = GObject.registerClass(
class Avatar extends St.Bin {
_init(user, params) {
- let themeContext = St.ThemeContext.get_for_stage(global.stage);
+ const themeContext = St.ThemeContext.get_for_stage(global.stage);
params = Params.parse(params, {
styleClass: 'user-icon',
reactive: false,
vfunc_style_changed() {
super.vfunc_style_changed();
- let node = this.get_theme_node();
- let [found, iconSize] = node.lookup_length('icon-size', false);
+ const node = this.get_theme_node();
+ const [found, iconSize] = node.lookup_length('icon-size', false);
if (!found)
return;
- let themeContext = St.ThemeContext.get_for_stage(global.stage);
+ const themeContext = St.ThemeContext.get_for_stage(global.stage);
// node.lookup_length() returns a scaled value, but we
// need unscaled
iconFile = null;
}
- let {scaleFactor} = St.ThemeContext.get_for_stage(global.stage);
+ const {scaleFactor} = St.ThemeContext.get_for_stage(global.stage);
this.set_size(
this._iconSize * scaleFactor,
this._iconSize * scaleFactor);
vfunc_allocate(box) {
this.set_allocation(box);
- let availWidth = box.x2 - box.x1;
- let availHeight = box.y2 - box.y1;
+ const availWidth = box.x2 - box.x1;
+ const availHeight = box.y2 - box.y1;
- let [, , natRealNameWidth] = this._realNameLabel.get_preferred_size();
+ const [, , natRealNameWidth] = this._realNameLabel.get_preferred_size();
- let childBox = new Clutter.ActorBox();
+ const childBox = new Clutter.ActorBox();
let hiddenLabel;
if (natRealNameWidth <= availWidth) {
// If user is null, that implies a username-based login authorization.
this._user = user;
- let vertical = orientation === Clutter.Orientation.VERTICAL;
- let xAlign = vertical ? Clutter.ActorAlign.CENTER : Clutter.ActorAlign.START;
- let styleClass = vertical ? 'user-widget vertical' : 'user-widget horizontal';
+ const vertical = orientation === Clutter.Orientation.VERTICAL;
+ const xAlign = vertical ? Clutter.ActorAlign.CENTER : Clutter.ActorAlign.START;
+ const styleClass = vertical ? 'user-widget vertical' : 'user-widget horizontal';
super._init({
styleClass,
}
_getTitleAndBanner(app, window) {
- let title = app.get_name();
- let banner = _('“%s” is ready').format(window.get_title());
+ const title = app.get_name();
+ const banner = _('“%s” is ready').format(window.get_title());
return [title, banner];
}
if (!window || window.has_focus() || window.is_skip_taskbar())
return;
- let app = this._tracker.get_window_app(window);
- let source = new WindowAttentionSource(app, window);
+ const app = this._tracker.get_window_app(window);
+ const source = new WindowAttentionSource(app, window);
Main.messageTray.add(source);
let [title, body] = this._getTitleAndBanner(app, window);
- let notification = new MessageTray.Notification({
+ const notification = new MessageTray.Notification({
source,
title,
body,
this._countDown = monitorManager.get_display_configuration_timeout();
// Translators: This string should be shorter than 30 characters
- let title = _('Keep these display settings?');
- let description = this._formatCountDown();
+ const title = _('Keep these display settings?');
+ const description = this._formatCountDown();
this._content = new Dialog.MessageDialogContent({title, description});
this.contentLayout.add_child(this._content);
}
_syncEnabled(dimmed) {
- let animating = this.actor.get_transition(`@effects.${this.name}.brightness`) !== null;
+ const animating = this.actor.get_transition(`@effects.${this.name}.brightness`) !== null;
this.enabled = Meta.prefs_get_attach_modal_dialogs() && (animating || dimmed);
}
setDimmed(dimmed, animate) {
- let val = 127 * (1 + (dimmed ? 1 : 0) * DIM_BRIGHTNESS);
+ const val = 127 * (1 + (dimmed ? 1 : 0) * DIM_BRIGHTNESS);
const color = new Cogl.Color({
red: val,
green: val,
this._pauseWorkspaceCheck = false;
- let tracker = Shell.WindowTracker.get_default();
+ const tracker = Shell.WindowTracker.get_default();
tracker.connect('startup-sequence-changed', this._queueCheckWorkspaces.bind(this));
- let workspaceManager = global.workspace_manager;
+ const workspaceManager = global.workspace_manager;
workspaceManager.connect('notify::n-workspaces',
this._nWorkspacesChanged.bind(this));
workspaceManager.connect('workspaces-reordered', () => {
}
_checkWorkspaces() {
- let workspaceManager = global.workspace_manager;
+ const workspaceManager = global.workspace_manager;
let i;
- let emptyWorkspaces = [];
+ const emptyWorkspaces = [];
if (!Meta.prefs_get_dynamic_workspaces()) {
this._checkWorkspacesId = 0;
return true;
for (i = 0; i < this._workspaces.length; i++) {
- let lastRemoved = this._workspaces[i]._lastRemovedWindow;
+ const lastRemoved = this._workspaces[i]._lastRemovedWindow;
if ((lastRemoved &&
(lastRemoved.get_window_type() === Meta.WindowType.SPLASHSCREEN ||
lastRemoved.get_window_type() === Meta.WindowType.DIALOG ||
emptyWorkspaces[i] = true;
}
- let sequences = Shell.WindowTracker.get_default().get_startup_sequences();
+ const sequences = Shell.WindowTracker.get_default().get_startup_sequences();
for (i = 0; i < sequences.length; i++) {
- let index = sequences[i].get_workspace();
+ const index = sequences[i].get_workspace();
if (index >= 0 && index <= workspaceManager.n_workspaces)
emptyWorkspaces[index] = false;
}
- let windows = global.get_window_actors();
+ const windows = global.get_window_actors();
for (i = 0; i < windows.length; i++) {
- let actor = windows[i];
- let win = actor.get_meta_window();
+ const actor = windows[i];
+ const win = actor.get_meta_window();
if (win.is_on_all_workspaces())
continue;
- let workspaceIndex = win.get_workspace().index();
+ const workspaceIndex = win.get_workspace().index();
emptyWorkspaces[workspaceIndex] = false;
}
emptyWorkspaces.push(true);
}
- let lastIndex = emptyWorkspaces.length - 1;
- let lastEmptyIndex = emptyWorkspaces.lastIndexOf(false) + 1;
- let activeWorkspaceIndex = workspaceManager.get_active_workspace_index();
+ const lastIndex = emptyWorkspaces.length - 1;
+ const lastEmptyIndex = emptyWorkspaces.lastIndexOf(false) + 1;
+ const activeWorkspaceIndex = workspaceManager.get_active_workspace_index();
emptyWorkspaces[activeWorkspaceIndex] = false;
// Delete empty workspaces except for the last one; do it from the end
_windowRemoved(workspace, window) {
workspace._lastRemovedWindow = window;
this._queueCheckWorkspaces();
- let id = GLib.timeout_add(GLib.PRIORITY_DEFAULT, LAST_WINDOW_GRACE_TIME, () => {
+ const id = GLib.timeout_add(GLib.PRIORITY_DEFAULT, LAST_WINDOW_GRACE_TIME, () => {
if (workspace._lastRemovedWindow === window) {
workspace._lastRemovedWindow = null;
this._queueCheckWorkspaces();
}
_nWorkspacesChanged() {
- let workspaceManager = global.workspace_manager;
- let oldNumWorkspaces = this._workspaces.length;
- let newNumWorkspaces = workspaceManager.n_workspaces;
+ const workspaceManager = global.workspace_manager;
+ const oldNumWorkspaces = this._workspaces.length;
+ const newNumWorkspaces = workspaceManager.n_workspaces;
if (oldNumWorkspaces === newNumWorkspaces)
return false;
// Assume workspaces are only removed sequentially
// (e.g. 2,3,4 - not 2,4,7)
let removedIndex;
- let removedNum = oldNumWorkspaces - newNumWorkspaces;
+ const removedNum = oldNumWorkspaces - newNumWorkspaces;
for (let w = 0; w < oldNumWorkspaces; w++) {
- let workspace = workspaceManager.get_workspace_by_index(w);
+ const workspace = workspaceManager.get_workspace_by_index(w);
if (this._workspaces[w] !== workspace) {
removedIndex = w;
break;
}
}
- let lostWorkspaces = this._workspaces.splice(removedIndex, removedNum);
+ const lostWorkspaces = this._workspaces.splice(removedIndex, removedNum);
lostWorkspaces.forEach(workspace => workspace.disconnectObject(this));
}
}
open(window, tileRect, monitorIndex) {
- let windowActor = window.get_compositor_private();
+ const windowActor = window.get_compositor_private();
if (!windowActor)
return;
if (this._rect && this._rect.equal(tileRect))
return;
- let changeMonitor = this._monitorIndex === -1 ||
+ const changeMonitor = this._monitorIndex === -1 ||
this._monitorIndex !== monitorIndex;
this._monitorIndex = monitorIndex;
this._rect = tileRect;
- let monitor = Main.layoutManager.monitors[monitorIndex];
+ const monitor = Main.layoutManager.monitors[monitorIndex];
this._updateStyle(monitor);
width: monitor.width,
height: monitor.height,
});
- let [, rect] = window.get_frame_rect().intersect(monitorRect);
+ const [, rect] = window.get_frame_rect().intersect(monitorRect);
this.set_size(rect.width, rect.height);
this.set_position(rect.x, rect.y);
this.opacity = 0;
}
_updateStyle(monitor) {
- let styles = ['tile-preview'];
+ const styles = ['tile-preview'];
if (this._monitorIndex === Main.layoutManager.primaryIndex)
styles.push('on-primary');
if (this._rect.x === monitor.x)
set(rect, displayW, displayH) {
/* Translators: This represents the size of a window. The first number is
* the width of the window and the second is the height. */
- let text = _('%d × %d').format(displayW, displayH);
+ const text = _('%d × %d').format(displayW, displayH);
this._label.set_text(text);
this.set_position(rect.x, rect.y);
global.display.connect('show-resize-popup', this._showResizePopup.bind(this));
global.display.connect('show-pad-osd', this._showPadOsd.bind(this));
global.display.connect('show-osd', (display, monitorIndex, iconName, label) => {
- let icon = Gio.Icon.new_for_string(iconName);
+ const icon = Gio.Icon.new_for_string(iconName);
Main.osdWindowManager.showOne(monitorIndex, icon, label);
});
return allowedModes & Main.actionMode;
});
topDragGesture.connect('end', () => {
- let currentWindow = global.display.focus_window;
+ const currentWindow = global.display.focus_window;
if (currentWindow)
currentWindow.unmake_fullscreen();
});
- let updateUnfullscreenGesture = () => {
- let currentWindow = global.display.focus_window;
+ const updateUnfullscreenGesture = () => {
+ const currentWindow = global.display.focus_window;
topDragGesture.enabled = currentWindow && currentWindow.is_fullscreen();
};
}
_switchApp() {
- let windows = global.get_window_actors().filter(actor => {
- let win = actor.metaWindow;
- let workspaceManager = global.workspace_manager;
- let activeWorkspace = workspaceManager.get_active_workspace();
+ const windows = global.get_window_actors().filter(actor => {
+ const win = actor.metaWindow;
+ const workspaceManager = global.workspace_manager;
+ const activeWorkspace = workspaceManager.get_active_workspace();
return !win.is_override_redirect() &&
win.located_on_workspace(activeWorkspace);
});
if (windows.length === 0)
return;
- let focusWindow = global.display.focus_window;
+ const focusWindow = global.display.focus_window;
let nextWindow;
if (focusWindow == null) {
}
insertWorkspace(pos) {
- let workspaceManager = global.workspace_manager;
+ const workspaceManager = global.workspace_manager;
if (!Meta.prefs_get_dynamic_workspaces())
return;
workspaceManager.append_new_workspace(false, global.get_current_time());
- let windows = global.get_window_actors().map(a => a.meta_window);
+ const windows = global.get_window_actors().map(a => a.meta_window);
// To create a new workspace, we slide all the windows on workspaces
// below us to the next workspace, leaving a blank workspace for us
if (window.on_all_workspaces)
return;
// Windows on workspaces below pos don't need moving
- let index = window.get_workspace().index();
+ const index = window.get_workspace().index();
if (index < pos)
return;
window.change_workspace_by_index(index + 1, true);
// If the new workspace was inserted before the active workspace,
// activate the workspace to which its windows went
- let activeIndex = workspaceManager.get_active_workspace_index();
+ const activeIndex = workspaceManager.get_active_workspace_index();
if (activeIndex >= pos) {
- let newWs = workspaceManager.get_workspace_by_index(activeIndex + 1);
+ const newWs = workspaceManager.get_workspace_by_index(activeIndex + 1);
this._blockAnimations = true;
newWs.activate(global.get_current_time());
this._blockAnimations = false;
}
addKeybinding(name, settings, flags, modes, handler) {
- let action = global.display.add_keybinding(name, settings, flags, handler);
+ const action = global.display.add_keybinding(name, settings, flags, handler);
if (action !== Meta.KeyBindingAction.NONE)
this.allowKeybinding(name, modes);
return action;
});
} else {
let xDest, yDest, xScale, yScale;
- let [success, geom] = actor.meta_window.get_icon_geometry();
+ const [success, geom] = actor.meta_window.get_icon_geometry();
if (success) {
xDest = geom.x;
yDest = geom.y;
xScale = geom.width / actor.width;
yScale = geom.height / actor.height;
} else {
- let monitor = Main.layoutManager.monitors[actor.meta_window.get_monitor()];
+ const monitor = Main.layoutManager.monitors[actor.meta_window.get_monitor()];
if (!monitor) {
this._minimizeWindowDone();
return;
onStopped: () => this._unminimizeWindowDone(shellwm, actor),
});
} else {
- let [success, geom] = actor.meta_window.get_icon_geometry();
+ const [success, geom] = actor.meta_window.get_icon_geometry();
if (success) {
actor.set_position(geom.x, geom.y);
actor.set_scale(
geom.width / actor.width,
geom.height / actor.height);
} else {
- let monitor = Main.layoutManager.monitors[actor.meta_window.get_monitor()];
+ const monitor = Main.layoutManager.monitors[actor.meta_window.get_monitor()];
if (!monitor) {
actor.show();
this._unminimizeWindowDone();
actor.set_scale(0, 0);
}
- let rect = actor.meta_window.get_buffer_rect();
- let [xDest, yDest] = [rect.x, rect.y];
+ const rect = actor.meta_window.get_buffer_rect();
+ const [xDest, yDest] = [rect.x, rect.y];
actor.show();
actor.ease({
_prepareAnimationInfo(shellwm, actor, oldFrameRect, _change) {
// Position a clone of the window on top of the old position,
// while actor updates are frozen.
- let actorContent = actor.paint_to_content(oldFrameRect);
- let actorClone = new St.Widget({content: actorContent});
+ const actorContent = actor.paint_to_content(oldFrameRect);
+ const actorClone = new St.Widget({content: actorContent});
actorClone.set_offscreen_redirect(Clutter.OffscreenRedirect.ALWAYS);
actorClone.set_position(oldFrameRect.x, oldFrameRect.y);
actorClone.set_size(oldFrameRect.width, oldFrameRect.height);
if (this._resizing.has(actor))
return;
- let actorClone = actor.__animationInfo.clone;
- let targetRect = actor.meta_window.get_frame_rect();
- let sourceRect = actor.__animationInfo.oldRect;
+ const actorClone = actor.__animationInfo.clone;
+ const targetRect = actor.meta_window.get_frame_rect();
+ const sourceRect = actor.__animationInfo.oldRect;
- let scaleX = targetRect.width / sourceRect.width;
- let scaleY = targetRect.height / sourceRect.height;
+ const scaleX = targetRect.width / sourceRect.width;
+ const scaleY = targetRect.height / sourceRect.height;
this._resizePending.delete(actor);
this._resizing.add(actor);
}
_dimWindow(window) {
- let actor = window.get_compositor_private();
+ const actor = window.get_compositor_private();
if (!actor)
return;
- let dimmer = getWindowDimmer(actor);
+ const dimmer = getWindowDimmer(actor);
if (!dimmer)
return;
dimmer.setDimmed(true, this._shouldAnimate());
}
_undimWindow(window) {
- let actor = window.get_compositor_private();
+ const actor = window.get_compositor_private();
if (!actor)
return;
- let dimmer = getWindowDimmer(actor);
+ const dimmer = getWindowDimmer(actor);
if (!dimmer)
return;
dimmer.setDimmed(false, this._shouldAnimate());
async _mapWindow(shellwm, actor) {
actor._windowType = actor.meta_window.get_window_type();
actor.meta_window.connectObject('notify::window-type', () => {
- let type = actor.meta_window.get_window_type();
+ const type = actor.meta_window.get_window_type();
if (type === actor._windowType)
return;
if (type === Meta.WindowType.MODAL_DIALOG ||
actor._windowType === Meta.WindowType.MODAL_DIALOG) {
- let parent = actor.get_meta_window().get_transient_for();
+ const parent = actor.get_meta_window().get_transient_for();
if (parent)
this._checkDimming(parent);
}
actor._windowType = type;
}, actor);
actor.meta_window.connect('unmanaged', window => {
- let parent = window.get_transient_for();
+ const parent = window.get_transient_for();
if (parent)
this._checkDimming(parent);
});
}
_destroyWindow(shellwm, actor) {
- let window = actor.meta_window;
+ const window = actor.meta_window;
window.disconnectObject(actor);
if (window.is_attached_dialog())
this._destroying.add(actor);
if (window.is_attached_dialog()) {
- let parent = window.get_transient_for();
+ const parent = window.get_transient_for();
parent.connectObject('unmanaged', () => {
actor.remove_all_transitions();
this._destroyWindowDone(shellwm, actor);
if (this._workspaceSwitcherPopup != null)
this._workspaceSwitcherPopup.destroy();
- let tabPopup = new constructor();
+ const tabPopup = new constructor();
if (!tabPopup.show(binding.is_reversed(), binding.get_name(), binding.get_mask()))
tabPopup.destroy();
}
_showWorkspaceSwitcher(display, window, event, binding) {
- let workspaceManager = display.get_workspace_manager();
+ const workspaceManager = display.get_workspace_manager();
if (!Main.sessionMode.hasWorkspaces)
return;
let [action,,, target] = binding.get_name().split('-');
let newWs;
let direction;
- let vertical = workspaceManager.layout_rows === -1;
- let rtl = Clutter.get_default_text_direction() === Clutter.TextDirection.RTL;
+ const vertical = workspaceManager.layout_rows === -1;
+ const rtl = Clutter.get_default_text_direction() === Clutter.TextDirection.RTL;
if (action === 'move') {
// "Moving" a window to another workspace doesn't make sense when
}
_confirmDisplayChange() {
- let dialog = new DisplayChangeDialog(this._shellwm);
+ const dialog = new DisplayChangeDialog(this._shellwm);
dialog.open();
}
}
_buildMenu(window) {
- let type = window.get_window_type();
+ const type = window.get_window_type();
let item;
if (Main.sessionMode.hasWorkspaces &&
(!Meta.prefs_get_workspaces_only_on_primary() ||
window.is_on_primary_monitor())) {
- let isSticky = window.is_on_all_workspaces();
+ const isSticky = window.is_on_all_workspaces();
item = this.addAction(_('Always on Visible Workspace'), () => {
if (isSticky)
item.setSensitive(false);
if (!isSticky) {
- let workspace = window.get_workspace();
+ const workspace = window.get_workspace();
if (workspace !== workspace.get_neighbor(Meta.MotionDirection.LEFT)) {
this.addAction(_('Move to Workspace Left'), () => {
- let dir = Meta.MotionDirection.LEFT;
+ const dir = Meta.MotionDirection.LEFT;
window.change_workspace(workspace.get_neighbor(dir));
});
}
if (workspace !== workspace.get_neighbor(Meta.MotionDirection.RIGHT)) {
this.addAction(_('Move to Workspace Right'), () => {
- let dir = Meta.MotionDirection.RIGHT;
+ const dir = Meta.MotionDirection.RIGHT;
window.change_workspace(workspace.get_neighbor(dir));
});
}
if (workspace !== workspace.get_neighbor(Meta.MotionDirection.UP)) {
this.addAction(_('Move to Workspace Up'), () => {
- let dir = Meta.MotionDirection.UP;
+ const dir = Meta.MotionDirection.UP;
window.change_workspace(workspace.get_neighbor(dir));
});
}
if (workspace !== workspace.get_neighbor(Meta.MotionDirection.DOWN)) {
this.addAction(_('Move to Workspace Down'), () => {
- let dir = Meta.MotionDirection.DOWN;
+ const dir = Meta.MotionDirection.DOWN;
window.change_workspace(workspace.get_neighbor(dir));
});
}
}
}
- let display = global.display;
- let nMonitors = display.get_n_monitors();
- let monitorIndex = window.get_monitor();
+ const display = global.display;
+ const nMonitors = display.get_n_monitors();
+ const monitorIndex = window.get_monitor();
if (nMonitors > 1 && monitorIndex >= 0) {
this.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());
let dir = Meta.DisplayDirection.UP;
- let upMonitorIndex =
+ const upMonitorIndex =
display.get_monitor_neighbor_index(monitorIndex, dir);
if (upMonitorIndex !== -1) {
this.addAction(_('Move to Monitor Up'), () => {
}
dir = Meta.DisplayDirection.DOWN;
- let downMonitorIndex =
+ const downMonitorIndex =
display.get_monitor_neighbor_index(monitorIndex, dir);
if (downMonitorIndex !== -1) {
this.addAction(_('Move to Monitor Down'), () => {
}
dir = Meta.DisplayDirection.LEFT;
- let leftMonitorIndex =
+ const leftMonitorIndex =
display.get_monitor_neighbor_index(monitorIndex, dir);
if (leftMonitorIndex !== -1) {
this.addAction(_('Move to Monitor Left'), () => {
}
dir = Meta.DisplayDirection.RIGHT;
- let rightMonitorIndex =
+ const rightMonitorIndex =
display.get_monitor_neighbor_index(monitorIndex, dir);
if (rightMonitorIndex !== -1) {
this.addAction(_('Move to Monitor Right'), () => {
if (type !== Meta.WindowMenuType.WM)
throw new Error('Unsupported window menu type');
- let menu = new WindowMenu(window, this._sourceActor);
+ const menu = new WindowMenu(window, this._sourceActor);
this._manager.addMenu(menu);
menu.connect('activate', () => {
window.check_alive(global.get_current_time());
});
- let destroyId = window.connect('unmanaged', () => {
+ const destroyId = window.connect('unmanaged', () => {
menu.close();
});
if (this.metaWindow.title)
return this.metaWindow.title;
- let tracker = Shell.WindowTracker.get_default();
- let app = tracker.get_window_app(this.metaWindow);
+ const tracker = Shell.WindowTracker.get_default();
+ const app = tracker.get_window_app(this.metaWindow);
return app.get_name();
}
}
_updateAttachedDialogs() {
- let iter = win => {
- let actor = win.get_compositor_private();
+ const iter = win => {
+ const actor = win.get_compositor_private();
if (!actor)
return false;
// We'll fix up the stack after the drag
return;
- let parent = this.get_parent();
- let actualAbove = this._getActualStackAbove();
+ const parent = this.get_parent();
+ const actualAbove = this._getActualStackAbove();
if (actualAbove == null)
parent.set_child_below_sibling(this, null);
else
}
vfunc_key_press_event(event) {
- let symbol = event.get_key_symbol();
- let isEnter = symbol === Clutter.KEY_Return || symbol === Clutter.KEY_KP_Enter;
+ const symbol = event.get_key_symbol();
+ const isEnter = symbol === Clutter.KEY_Return || symbol === Clutter.KEY_KP_Enter;
if (isEnter) {
this._activate();
return true;
// thumbnails is much more important to preserve than the width of
// them, so two windows with equal height, but maybe differering
// widths line up.
- let ratio = window.boundingBox.height / this._monitor.height;
+ const ratio = window.boundingBox.height / this._monitor.height;
// The purpose of this manipulation here is to prevent windows
// from getting too small. For something like a calculator window,
}
_computeRowSizes(layout) {
- let {rows, scale} = layout;
+ const {rows, scale} = layout;
for (let i = 0; i < rows.length; i++) {
- let row = rows[i];
+ const row = rows[i];
row.width = row.fullWidth * scale + (row.windows.length - 1) * this._columnSpacing;
row.height = row.fullHeight * scale;
}
if (row.fullWidth + width <= idealRowWidth)
return true;
- let oldRatio = row.fullWidth / idealRowWidth;
- let newRatio = (row.fullWidth + width) / idealRowWidth;
+ const oldRatio = row.fullWidth / idealRowWidth;
+ const newRatio = (row.fullWidth + width) / idealRowWidth;
if (Math.abs(1 - newRatio) < Math.abs(1 - oldRatio))
return true;
const numRows = layoutParams.numRows;
- let rows = [];
+ const rows = [];
let totalWidth = 0;
for (let i = 0; i < windows.length; i++) {
- let window = windows[i];
- let s = this._computeWindowScale(window);
+ const window = windows[i];
+ const s = this._computeWindowScale(window);
totalWidth += window.boundingBox.width * s;
}
- let idealRowWidth = totalWidth / numRows;
+ const idealRowWidth = totalWidth / numRows;
// Sort windows vertically to minimize travel distance.
// This affects what rows the windows get placed in.
- let sortedWindows = windows.slice();
+ const sortedWindows = windows.slice();
sortedWindows.sort((a, b) => a.windowCenter.y - b.windowCenter.y);
let windowIdx = 0;
for (let i = 0; i < numRows; i++) {
- let row = this._newRow();
+ const row = this._newRow();
rows.push(row);
for (; windowIdx < sortedWindows.length; windowIdx++) {
- let window = sortedWindows[windowIdx];
- let s = this._computeWindowScale(window);
- let width = window.boundingBox.width * s;
- let height = window.boundingBox.height * s;
+ const window = sortedWindows[windowIdx];
+ const s = this._computeWindowScale(window);
+ const width = window.boundingBox.width * s;
+ const height = window.boundingBox.height * s;
row.fullHeight = Math.max(row.fullHeight, height);
// either new width is < idealWidth or new width is nearer from idealWidth then oldWidth
let gridHeight = 0;
let maxRow;
for (let i = 0; i < numRows; i++) {
- let row = rows[i];
+ const row = rows[i];
this._sortRow(row);
if (!maxRow || row.fullWidth > maxRow.fullWidth)
}
computeScaleAndSpace(layout, area) {
- let hspacing = (layout.maxColumns - 1) * this._columnSpacing;
- let vspacing = (layout.numRows - 1) * this._rowSpacing;
+ const hspacing = (layout.maxColumns - 1) * this._columnSpacing;
+ const vspacing = (layout.numRows - 1) * this._rowSpacing;
- let spacedWidth = area.width - hspacing;
- let spacedHeight = area.height - vspacing;
+ const spacedWidth = area.width - hspacing;
+ const spacedHeight = area.height - vspacing;
- let horizontalScale = spacedWidth / layout.gridWidth;
- let verticalScale = spacedHeight / layout.gridHeight;
+ const horizontalScale = spacedWidth / layout.gridWidth;
+ const verticalScale = spacedHeight / layout.gridHeight;
// Thumbnails should be less than 70% of the original size
- let scale = Math.min(
+ const scale = Math.min(
horizontalScale, verticalScale, WINDOW_PREVIEW_MAXIMUM_SCALE);
- let scaledLayoutWidth = layout.gridWidth * scale + hspacing;
- let scaledLayoutHeight = layout.gridHeight * scale + vspacing;
- let space = (scaledLayoutWidth * scaledLayoutHeight) / (area.width * area.height);
+ const scaledLayoutWidth = layout.gridWidth * scale + hspacing;
+ const scaledLayoutHeight = layout.gridHeight * scale + vspacing;
+ const space = (scaledLayoutWidth * scaledLayoutHeight) / (area.width * area.height);
layout.scale = scale;
computeWindowSlots(layout, area) {
this._computeRowSizes(layout);
- let {rows, scale} = layout;
+ const {rows, scale} = layout;
- let slots = [];
+ const slots = [];
// Do this in three parts.
let heightWithoutSpacing = 0;
for (let i = 0; i < rows.length; i++) {
- let row = rows[i];
+ const row = rows[i];
heightWithoutSpacing += row.height;
}
- let verticalSpacing = (rows.length - 1) * this._rowSpacing;
- let additionalVerticalScale = Math.min(1, (area.height - verticalSpacing) / heightWithoutSpacing);
+ const verticalSpacing = (rows.length - 1) * this._rowSpacing;
+ const additionalVerticalScale = Math.min(1, (area.height - verticalSpacing) / heightWithoutSpacing);
// keep track how much smaller the grid becomes due to scaling
// so it can be centered again
let y = 0;
for (let i = 0; i < rows.length; i++) {
- let row = rows[i];
+ const row = rows[i];
// If this window layout row doesn't fit in the actual
// geometry, then apply an additional scale to it.
- let horizontalSpacing = (row.windows.length - 1) * this._columnSpacing;
- let widthWithoutSpacing = row.width - horizontalSpacing;
- let additionalHorizontalScale = Math.min(1, (area.width - horizontalSpacing) / widthWithoutSpacing);
+ const horizontalSpacing = (row.windows.length - 1) * this._columnSpacing;
+ const widthWithoutSpacing = row.width - horizontalSpacing;
+ const additionalHorizontalScale = Math.min(1, (area.width - horizontalSpacing) / widthWithoutSpacing);
if (additionalHorizontalScale < additionalVerticalScale) {
row.additionalScale = additionalHorizontalScale;
let x = row.x;
for (let j = 0; j < row.windows.length; j++) {
- let window = row.windows[j];
+ const window = row.windows[j];
let s = scale * this._computeWindowScale(window) * row.additionalScale;
- let cellWidth = window.boundingBox.width * s;
- let cellHeight = window.boundingBox.height * s;
+ const cellWidth = window.boundingBox.width * s;
+ const cellHeight = window.boundingBox.height * s;
s = Math.min(s, WINDOW_PREVIEW_MAXIMUM_SCALE);
- let cloneWidth = window.boundingBox.width * s;
+ const cloneWidth = window.boundingBox.width * s;
const cloneHeight = window.boundingBox.height * s;
let cloneX = x + (cellWidth - cloneWidth) / 2;
}
_isBetterScaleAndSpace(oldScale, oldSpace, scale, space) {
- let spacePower = (space - oldSpace) * LAYOUT_SPACE_WEIGHT;
- let scalePower = (scale - oldScale) * LAYOUT_SCALE_WEIGHT;
+ const spacePower = (space - oldSpace) * LAYOUT_SPACE_WEIGHT;
+ const scalePower = (scale - oldScale) * LAYOUT_SCALE_WEIGHT;
if (scale > oldScale && space > oldSpace) {
// Win win -- better scale and better space
}
_doRemoveWindow(metaWin) {
- let clone = this._removeWindowClone(metaWin);
+ const clone = this._removeWindowClone(metaWin);
if (!clone)
return;
}
_doAddWindow(metaWin) {
- let win = metaWin.get_compositor_private();
+ const win = metaWin.get_compositor_private();
if (!win) {
// Newly-created windows are added to a workspace before
// the compositor finds out about them...
- let id = GLib.idle_add(GLib.PRIORITY_DEFAULT, () => {
+ const id = GLib.idle_add(GLib.PRIORITY_DEFAULT, () => {
if (metaWin.get_compositor_private() &&
metaWin.get_workspace() === this.metaWorkspace)
this._doAddWindow(metaWin);
return;
// Let the top-most ancestor handle all transients
- let parent = metaWin.find_root_ancestor();
- let clone = this._windows.find(c => c.metaWindow === parent);
+ const parent = metaWin.find_root_ancestor();
+ const clone = this._windows.find(c => c.metaWindow === parent);
// If no clone was found, the parent hasn't been created yet
// and will take care of the dialog when added
// Create a clone of a (non-desktop) window and add it to the window list
_addWindowClone(metaWindow) {
- let clone = new WindowPreview(metaWindow, this, this._overviewAdjustment);
+ const clone = new WindowPreview(metaWindow, this, this._overviewAdjustment);
clone.connect('selected',
this._onCloneSelected.bind(this));
Main.overview.endWindowDrag(metaWindow);
});
clone.connect('show-chrome', () => {
- let focus = global.stage.key_focus;
+ const focus = global.stage.key_focus;
if (focus == null || this.contains(focus))
clone.grab_key_focus();
_removeWindowClone(metaWin) {
// find the position of the window in our list
- let index = this._lookupIndex(metaWin);
+ const index = this._lookupIndex(metaWin);
if (index === -1)
return null;
}
acceptDrop(source, actor, x, y, time) {
- let workspaceManager = global.workspace_manager;
- let workspaceIndex = this.metaWorkspace
+ const workspaceManager = global.workspace_manager;
+ const workspaceIndex = this.metaWorkspace
? this.metaWorkspace.index()
: workspaceManager.get_active_workspace_index();
},
}, class WindowClone extends Clutter.Actor {
_init(realWindow) {
- let clone = new Clutter.Clone({source: realWindow});
+ const clone = new Clutter.Clone({source: realWindow});
super._init({
layout_manager: new PrimaryActorLayout(clone),
reactive: true,
() => this.emit('selected', Clutter.get_current_event_time()));
this.add_action(clickGesture);
- let iter = win => {
- let actor = win.get_compositor_private();
+ const iter = win => {
+ const actor = win.get_compositor_private();
if (!actor)
return false;
if (actor.inDrag)
return;
- let parent = this.get_parent();
- let actualAbove = this.getActualStackAbove();
+ const parent = this.get_parent();
+ const actualAbove = this.getActualStackAbove();
if (actualAbove == null)
parent.set_child_below_sibling(this, null);
else
}
_doAddAttachedDialog(metaDialog, realDialog) {
- let clone = new Clutter.Clone({source: realDialog});
+ const clone = new Clutter.Clone({source: realDialog});
this._updateDialogPosition(realDialog, clone);
realDialog.connectObject(
}
_updateDialogPosition(realDialog, cloneDialog) {
- let metaDialog = realDialog.meta_window;
- let dialogRect = metaDialog.get_frame_rect();
- let rect = this.metaWindow.get_frame_rect();
+ const metaDialog = realDialog.meta_window;
+ const dialogRect = metaDialog.get_frame_rect();
+ const rect = this.metaWindow.get_frame_rect();
cloneDialog.set_position(dialogRect.x - rect.x, dialogRect.y - rect.y);
}
// We may not have a parent if DnD completed successfully, in
// which case our clone will shortly be destroyed and replaced
// with a new one on the target workspace.
- let parent = this.get_parent();
+ const parent = this.get_parent();
if (parent !== null) {
if (this._stackAbove == null)
parent.set_child_below_sibling(this, null);
this.connect('destroy', this._onDestroy.bind(this));
- let workArea = Main.layoutManager.getWorkAreaForMonitor(this.monitorIndex);
+ const workArea = Main.layoutManager.getWorkAreaForMonitor(this.monitorIndex);
this.setPorthole(workArea.x, workArea.y, workArea.width, workArea.height);
- let windows = global.get_window_actors().filter(actor => {
- let win = actor.meta_window;
+ const windows = global.get_window_actors().filter(actor => {
+ const win = actor.meta_window;
return win.located_on_workspace(metaWorkspace);
});
syncStacking(stackIndices) {
this._windows.sort((a, b) => {
- let indexA = stackIndices[a.metaWindow.get_stable_sequence()];
- let indexB = stackIndices[b.metaWindow.get_stable_sequence()];
+ const indexA = stackIndices[a.metaWindow.get_stable_sequence()];
+ const indexB = stackIndices[b.metaWindow.get_stable_sequence()];
return indexA - indexB;
});
for (let i = 1; i < this._windows.length; i++) {
- let clone = this._windows[i];
+ const clone = this._windows[i];
const previousClone = this._windows[i - 1];
clone.setStackAbove(previousClone);
}
}
_doRemoveWindow(metaWin) {
- let clone = this._removeWindowClone(metaWin);
+ const clone = this._removeWindowClone(metaWin);
if (clone)
clone.destroy();
}
if (this._removed)
return;
- let win = metaWin.get_compositor_private();
+ const win = metaWin.get_compositor_private();
if (!win) {
// Newly-created windows are added to a workspace before
// the compositor finds out about them...
- let id = GLib.idle_add(GLib.PRIORITY_DEFAULT, () => {
+ const id = GLib.idle_add(GLib.PRIORITY_DEFAULT, () => {
if (!this._removed &&
metaWin.get_compositor_private() &&
metaWin.get_workspace() === this.metaWorkspace)
while (parent.is_attached_dialog())
parent = parent.get_transient_for();
- let idx = this._lookupIndex(parent);
+ const idx = this._lookupIndex(parent);
if (idx < 0) {
// parent was not created yet, it will take care
// of the dialog when created
return;
}
- let clone = this._windows[idx];
+ const clone = this._windows[idx];
clone.addAttachedDialog(metaWin);
}
}
}
_windowRemoved(metaWorkspace, metaWin) {
- let index = this._allWindows.indexOf(metaWin);
+ const index = this._allWindows.indexOf(metaWin);
if (index !== -1) {
metaWin.disconnectObject(this);
this._allWindows.splice(index, 1);
// Tests if @actor belongs to this workspace and monitor
_isMyWindow(actor) {
- let win = actor.meta_window;
+ const win = actor.meta_window;
return win.located_on_workspace(this.metaWorkspace) &&
(win.get_monitor() === this.monitorIndex);
}
// Create a clone of a (non-desktop) window and add it to the window list
_addWindowClone(win) {
- let clone = new WindowClone(win);
+ const clone = new WindowClone(win);
clone.connect('selected', (o, time) => {
this.activate(time);
_removeWindowClone(metaWin) {
// find the position of the window in our list
- let index = this._lookupIndex(metaWin);
+ const index = this._lookupIndex(metaWin);
if (index === -1)
return null;
return false;
if (source.metaWindow) {
- let win = source.metaWindow.get_compositor_private();
+ const win = source.metaWindow.get_compositor_private();
if (this._isMyWindow(win))
return false;
- let metaWindow = win.get_meta_window();
+ const metaWindow = win.get_meta_window();
Main.moveWindowToMonitorAndWorkspace(metaWindow,
this.monitorIndex, this.metaWorkspace.index());
return true;
this._delegate = this;
- let indicator = new St.Bin({style_class: 'workspace-thumbnail-indicator'});
+ const indicator = new St.Bin({style_class: 'workspace-thumbnail-indicator'});
// We don't want the indicator to affect drag-and-drop
Shell.util_set_hidden_from_pick(indicator, true);
this._shouldShow = true;
this._stateCounts = {};
- for (let key in ThumbnailState)
+ for (const key in ThumbnailState)
this._stateCounts[ThumbnailState[key]] = 0;
this._thumbnails = [];
return DND.DragMotionResult.CONTINUE;
const rtl = Clutter.get_default_text_direction() === Clutter.TextDirection.RTL;
- let canCreateWorkspaces = Meta.prefs_get_dynamic_workspaces();
- let spacing = this.get_theme_node().get_length('spacing');
+ const canCreateWorkspaces = Meta.prefs_get_dynamic_workspaces();
+ const spacing = this.get_theme_node().get_length('spacing');
this._dropWorkspace = -1;
let placeholderPos = -1;
- let length = this._thumbnails.length;
+ const length = this._thumbnails.length;
for (let i = 0; i < length; i++) {
const index = rtl ? length - i - 1 : i;
(source.app || !source.shellWorkspaceLaunch))
return false;
- let isWindow = !!source.metaWindow;
+ const isWindow = !!source.metaWindow;
let newWorkspaceIndex;
[newWorkspaceIndex, this._dropPlaceholderPos] = [this._dropPlaceholderPos, -1];
if (isWindow) {
// Move the window to our monitor first if necessary.
- let thumbMonitor = this._thumbnails[newWorkspaceIndex].monitorIndex;
+ const thumbMonitor = this._thumbnails[newWorkspaceIndex].monitorIndex;
Main.moveWindowToMonitorAndWorkspace(source.metaWindow,
thumbMonitor, newWorkspaceIndex, true);
} else if (source.app && source.app.can_open_new_window()) {
// to open its first window within some time, as tracked by Shell.WindowTracker.
// Here, we only add a very brief timeout to avoid the _immediate_ removal of the
// workspace while we wait for the startup sequence to load.
- let workspaceManager = global.workspace_manager;
+ const workspaceManager = global.workspace_manager;
Main.wm.keepWorkspaceAlive(workspaceManager.get_workspace_by_index(newWorkspaceIndex),
WORKSPACE_KEEP_ALIVE_TIME);
}
// Start the animation on the workspace (which is actually
// an old one which just became empty)
- let thumbnail = this._thumbnails[newWorkspaceIndex];
+ const thumbnail = this._thumbnails[newWorkspaceIndex];
this._setThumbnailState(thumbnail, ThumbnailState.NEW);
thumbnail.slide_position = 1;
thumbnail.collapse_fraction = 1;
this._unqueueUpdateStates();
this._stateCounts = {};
- for (let key in ThumbnailState)
+ for (const key in ThumbnailState)
this._stateCounts[ThumbnailState[key]] = 0;
this.addThumbnails(0, workspaceManager.n_workspaces);
}
_workspacesChanged() {
- let validThumbnails =
+ const validThumbnails =
this._thumbnails.filter(t => t.state <= ThumbnailState.NORMAL);
- let workspaceManager = global.workspace_manager;
- let oldNumWorkspaces = validThumbnails.length;
- let newNumWorkspaces = workspaceManager.n_workspaces;
+ const workspaceManager = global.workspace_manager;
+ const oldNumWorkspaces = validThumbnails.length;
+ const newNumWorkspaces = workspaceManager.n_workspaces;
if (newNumWorkspaces > oldNumWorkspaces) {
this.addThumbnails(oldNumWorkspaces, newNumWorkspaces - oldNumWorkspaces);
} else {
let removedIndex;
- let removedNum = oldNumWorkspaces - newNumWorkspaces;
+ const removedNum = oldNumWorkspaces - newNumWorkspaces;
for (let w = 0; w < oldNumWorkspaces; w++) {
- let metaWorkspace = workspaceManager.get_workspace_by_index(w);
+ const metaWorkspace = workspaceManager.get_workspace_by_index(w);
if (this._thumbnails[w].metaWorkspace !== metaWorkspace) {
removedIndex = w;
break;
}
addThumbnails(start, count) {
- let workspaceManager = global.workspace_manager;
+ const workspaceManager = global.workspace_manager;
for (let k = start; k < start + count; k++) {
- let metaWorkspace = workspaceManager.get_workspace_by_index(k);
- let thumbnail = new WorkspaceThumbnail(metaWorkspace, this._monitorIndex);
+ const metaWorkspace = workspaceManager.get_workspace_by_index(k);
+ const thumbnail = new WorkspaceThumbnail(metaWorkspace, this._monitorIndex);
thumbnail.setPorthole(
this._porthole.x, this._porthole.y,
this._porthole.width, this._porthole.height);
removeThumbnails(start, count) {
let currentPos = 0;
for (let k = 0; k < this._thumbnails.length; k++) {
- let thumbnail = this._thumbnails[k];
+ const thumbnail = this._thumbnails[k];
if (thumbnail.state > ThumbnailState.NORMAL)
continue;
this._stateCounts[thumbnail.state]--;
thumbnail.state = ThumbnailState.DESTROYED;
- let index = this._thumbnails.indexOf(thumbnail);
+ const index = this._thumbnails.indexOf(thumbnail);
this._thumbnails.splice(index, 1);
thumbnail.destroy();
}
vfunc_get_preferred_height(forWidth) {
- let themeNode = this.get_theme_node();
+ const themeNode = this.get_theme_node();
forWidth = themeNode.adjust_for_width(forWidth);
- let spacing = themeNode.get_length('spacing');
- let nWorkspaces = this._thumbnails.length;
- let totalSpacing = (nWorkspaces - 1) * spacing;
+ const spacing = themeNode.get_length('spacing');
+ const nWorkspaces = this._thumbnails.length;
+ const totalSpacing = (nWorkspaces - 1) * spacing;
const avail = forWidth - totalSpacing;
// Note that for getPreferredHeight/Width we cheat a bit and skip propagating
// the size request to our children because we know how big they are and know
// that the actors aren't depending on the virtual functions being called.
- let themeNode = this.get_theme_node();
+ const themeNode = this.get_theme_node();
- let spacing = themeNode.get_length('spacing');
- let nWorkspaces = this._thumbnails.length;
- let totalSpacing = (nWorkspaces - 1) * spacing;
+ const spacing = themeNode.get_length('spacing');
+ const nWorkspaces = this._thumbnails.length;
+ const totalSpacing = (nWorkspaces - 1) * spacing;
const naturalWidth = this._thumbnails.reduce((accumulator, thumbnail, index) => {
let workspaceSpacing = 0;
vfunc_allocate(box) {
this.set_allocation(box);
- let rtl = Clutter.get_default_text_direction() === Clutter.TextDirection.RTL;
+ const rtl = Clutter.get_default_text_direction() === Clutter.TextDirection.RTL;
if (this._thumbnails.length === 0) // not visible
return;
- let themeNode = this.get_theme_node();
+ const themeNode = this.get_theme_node();
box = themeNode.get_content_box(box);
const portholeWidth = this._porthole.width;
box.x1 += Math.round(extraWidth / 2);
box.x2 -= Math.round(extraWidth / 2);
- let indicatorValue = this._scrollAdjustment.value;
- let indicatorUpperWs = Math.ceil(indicatorValue);
- let indicatorLowerWs = Math.floor(indicatorValue);
+ const indicatorValue = this._scrollAdjustment.value;
+ const indicatorUpperWs = Math.ceil(indicatorValue);
+ const indicatorLowerWs = Math.floor(indicatorValue);
let indicatorLowerX1 = 0;
let indicatorLowerX2 = 0;
let indicatorUpperX1 = 0;
let indicatorUpperX2 = 0;
- let indicatorThemeNode = this._indicator.get_theme_node();
- let indicatorTopFullBorder = indicatorThemeNode.get_padding(St.Side.TOP) + indicatorThemeNode.get_border_width(St.Side.TOP);
- let indicatorBottomFullBorder = indicatorThemeNode.get_padding(St.Side.BOTTOM) + indicatorThemeNode.get_border_width(St.Side.BOTTOM);
- let indicatorLeftFullBorder = indicatorThemeNode.get_padding(St.Side.LEFT) + indicatorThemeNode.get_border_width(St.Side.LEFT);
- let indicatorRightFullBorder = indicatorThemeNode.get_padding(St.Side.RIGHT) + indicatorThemeNode.get_border_width(St.Side.RIGHT);
+ const indicatorThemeNode = this._indicator.get_theme_node();
+ const indicatorTopFullBorder = indicatorThemeNode.get_padding(St.Side.TOP) + indicatorThemeNode.get_border_width(St.Side.TOP);
+ const indicatorBottomFullBorder = indicatorThemeNode.get_padding(St.Side.BOTTOM) + indicatorThemeNode.get_border_width(St.Side.BOTTOM);
+ const indicatorLeftFullBorder = indicatorThemeNode.get_padding(St.Side.LEFT) + indicatorThemeNode.get_border_width(St.Side.LEFT);
+ const indicatorRightFullBorder = indicatorThemeNode.get_padding(St.Side.RIGHT) + indicatorThemeNode.get_border_width(St.Side.RIGHT);
let x = box.x1;
});
}
- let childBox = new Clutter.ActorBox();
+ const childBox = new Clutter.ActorBox();
for (let i = 0; i < this._thumbnails.length; i++) {
const thumbnail = this._thumbnails[i];
export const WorkspacesView = GObject.registerClass(
class WorkspacesView extends WorkspacesViewBase {
_init(monitorIndex, controls, scrollAdjustment, fitModeAdjustment, overviewAdjustment) {
- let workspaceManager = global.workspace_manager;
+ const workspaceManager = global.workspace_manager;
super._init(monitorIndex, overviewAdjustment);
if (vertical) {
const availableHeight = height - spacing * (nWorkspaces + 1);
let workspaceHeight = availableHeight / nWorkspaces;
- let [, workspaceWidth] =
+ const [, workspaceWidth] =
workspace.get_preferred_width(workspaceHeight);
y1 = spacing;
} else {
const availableWidth = width - spacing * (nWorkspaces + 1);
let workspaceWidth = availableWidth / nWorkspaces;
- let [, workspaceHeight] =
+ const [, workspaceHeight] =
workspace.get_preferred_height(workspaceWidth);
x1 = spacing;
}
getActiveWorkspace() {
- let workspaceManager = global.workspace_manager;
- let active = workspaceManager.get_active_workspace_index();
+ const workspaceManager = global.workspace_manager;
+ const active = workspaceManager.get_active_workspace_index();
return this._workspaces[active];
}
}
_updateVisibility() {
- let workspaceManager = global.workspace_manager;
- let active = workspaceManager.get_active_workspace_index();
+ const workspaceManager = global.workspace_manager;
+ const active = workspaceManager.get_active_workspace_index();
const fitMode = this._fitModeAdjustment.value;
const singleFitMode = fitMode === FitMode.SINGLE;
for (let w = 0; w < this._workspaces.length; w++) {
- let workspace = this._workspaces[w];
+ const workspace = this._workspaces[w];
if (this._animating || this._gestureActive || !singleFitMode)
workspace.show();
}
_updateWorkspaces() {
- let workspaceManager = global.workspace_manager;
- let newNumWorkspaces = workspaceManager.n_workspaces;
+ const workspaceManager = global.workspace_manager;
+ const newNumWorkspaces = workspaceManager.n_workspaces;
for (let j = 0; j < newNumWorkspaces; j++) {
- let metaWorkspace = workspaceManager.get_workspace_by_index(j);
+ const metaWorkspace = workspaceManager.get_workspace_by_index(j);
let workspace;
if (j >= this._workspaces.length) { /* added */
const allowSwitch =
adj.get_transition('value') === null && !this._gestureActive;
- let workspaceManager = global.workspace_manager;
- let active = workspaceManager.get_active_workspace_index();
+ const workspaceManager = global.workspace_manager;
+ const active = workspaceManager.get_active_workspace_index();
let current = Math.round(adj.value);
if (allowSwitch && active !== current) {
current = this._workspaces.length - 1;
}
- let metaWorkspace = this._workspaces[current].metaWorkspace;
+ const metaWorkspace = this._workspaces[current].metaWorkspace;
metaWorkspace.activate(global.get_current_time());
}
upper: FitMode.ALL,
});
- let workspaceManager = global.workspace_manager;
+ const workspaceManager = global.workspace_manager;
this._scrollAdjustment = scrollAdjustment;
global.window_manager.connectObject('switch-workspace',
}
_workspacesReordered() {
- let workspaceManager = global.workspace_manager;
+ const workspaceManager = global.workspace_manager;
this._scrollAdjustment.value =
workspaceManager.get_active_workspace_index();
if (this._workspacesOnlyOnPrimary && monitor !== this._primaryIndex)
return;
- let workspaceManager = global.workspace_manager;
- let adjustment = this._scrollAdjustment;
+ const workspaceManager = global.workspace_manager;
+ const adjustment = this._scrollAdjustment;
if (this._gestureActive)
adjustment.remove_transition('value');
for (let i = 0; i < this._workspacesViews.length; i++)
this._workspacesViews[i].startTouchGesture();
- let progress = adjustment.value / adjustment.page_size;
- let points = Array.from(
+ const progress = adjustment.value / adjustment.page_size;
+ const points = Array.from(
{length: workspaceManager.n_workspaces}, (v, i) => i);
tracker.confirmSwipe(distance, points, progress, Math.round(progress));
}
_switchWorkspaceUpdate(tracker, progress) {
- let adjustment = this._scrollAdjustment;
+ const adjustment = this._scrollAdjustment;
adjustment.value = progress * adjustment.page_size;
}
_switchWorkspaceEnd(tracker, duration, endProgress) {
- let workspaceManager = global.workspace_manager;
- let newWs = workspaceManager.get_workspace_by_index(endProgress);
+ const workspaceManager = global.workspace_manager;
+ const newWs = workspaceManager.get_workspace_by_index(endProgress);
this._scrollAdjustment.ease(endProgress, {
mode: Clutter.AnimationMode.EASE_OUT_CUBIC,
this._primaryIndex = Main.layoutManager.primaryIndex;
this._workspacesViews = [];
- let monitors = Main.layoutManager.monitors;
+ const monitors = Main.layoutManager.monitors;
for (let i = 0; i < monitors.length; i++) {
let view;
if (i === this._primaryIndex) {
}
_getMonitorIndexForEvent(event) {
- let [x, y] = event.get_coords();
+ const [x, y] = event.get_coords();
const rect = new Mtk.Rectangle({x, y, width: 1, height: 1});
return global.display.get_monitor_index_for_rect(rect);
}
if (this._cursorWindowClone)
return;
- let windows = global.get_window_actors();
- let cursorWindow = windows[windows.length - 1];
+ const windows = global.get_window_actors();
+ const cursorWindow = windows[windows.length - 1];
// FIXME: more reliable way?
if (!cursorWindow.get_meta_window().is_override_redirect())
if (this._cursorWindowClone)
Main.uiGroup.set_child_above_sibling(this._cursorWindowClone, null);
- let dragEvent = {
+ const dragEvent = {
x,
y,
dragActor: this._cursorWindowClone ?? this._dummy,
};
for (let i = 0; i < DND.dragMonitors.length; i++) {
- let motionFunc = DND.dragMonitors[i].dragMotion;
+ const motionFunc = DND.dragMonitors[i].dragMotion;
if (motionFunc) {
- let result = motionFunc(dragEvent);
+ const result = motionFunc(dragEvent);
if (result !== DND.DragMotionResult.CONTINUE)
return;
}
while (pickedActor) {
if (pickedActor._delegate && pickedActor._delegate.handleDragOver) {
- let [r_, targX, targY] = pickedActor.transform_stage_point(x, y);
- let result = pickedActor._delegate.handleDragOver(this,
+ const [r_, targX, targY] = pickedActor.transform_stage_point(x, y);
+ const result = pickedActor._delegate.handleDragOver(this,
dragEvent.dragActor,
targX,
targY,
const f = Gio.File.new_for_uri(uri);
try {
- let [ok_, bytes] = f.load_contents(null);
+ const [ok_, bytes] = f.load_contents(null);
return new TextDecoder().decode(bytes);
} catch {
console.error(`Failed to load D-Bus interface ${iface}`);
async _loadExtensions() {
const [extensionsMap] = await this._shellProxy.ListExtensionsAsync();
- for (let uuid in extensionsMap) {
+ for (const uuid in extensionsMap) {
const extension = new Extension(extensionsMap[uuid]);
this._extensions.append(extension);
}
style_class: 'system-status-icon',
}));
- let item = new PopupMenu.PopupMenuItem(_('Show Notification'));
+ const item = new PopupMenu.PopupMenuItem(_('Show Notification'));
item.connect('activate', () => {
Main.notify(_('Whatʼs up, folks?'));
});
// to calculate the mipmaps for the windows, the second time to get
// a clean set of numbers.
if ((i % 2) === 0) {
- let config = WINDOW_CONFIGS[i / 2];
+ const config = WINDOW_CONFIGS[i / 2];
await Scripting.destroyTestWindows();
for (let k = 0; k < config.count; k++) {
let overviewLatency;
let mallocUsedSize = 0;
let overviewShowCount = 0;
-let haveSwapComplete = false;
+const haveSwapComplete = false;
let applicationsShowStart;
let applicationsShowCount = 0;
finishedShowingOverview = false;
overviewShowCount++;
- let dt = (time - (overviewShowStart + overviewLatency)) / 1000000;
+ const dt = (time - (overviewShowStart + overviewLatency)) / 1000000;
// If we see a start frame and an end frame, that would
// be 1 frame for a FPS computation, hence the '- 1'
- let fps = (overviewFrames - 1) / dt;
+ const fps = (overviewFrames - 1) / dt;
if (overviewShowCount === 1) {
METRICS.overviewLatencyFirst.value = overviewLatency;
// Other than overviewFpsFirst, we collect FPS metrics the second
// we show each window configuration. overviewShowCount is 1,2,3...
if (overviewShowCount % 2 === 0) {
- let config = WINDOW_CONFIGS[(overviewShowCount / 2) - 1];
+ const config = WINDOW_CONFIGS[(overviewShowCount / 2) - 1];
METRICS[config.metric].value = fps;
}
}
function waitAndDraw(milliseconds) {
let cb;
- let timeline = new Clutter.Timeline({duration: milliseconds});
+ const timeline = new Clutter.Timeline({duration: milliseconds});
timeline.start();
timeline.connect('new-frame', (_timeline, _frame) => {
function waitSignal(object, signal) {
let cb;
- let id = object.connect(signal, () => {
+ const id = object.connect(signal, () => {
object.disconnect(id);
if (cb)
cb();
], Gio.SubprocessFlags.STDOUT_PIPE);
let result = null;
- let datastream = Gio.DataInputStream.new(sp.get_stdout_pipe());
+ const datastream = Gio.DataInputStream.new(sp.get_stdout_pipe());
while (true) {
- let [line, length_] = datastream.read_line_utf8(null);
+ const [line, length_] = datastream.read_line_utf8(null);
if (line === null)
break;
- let fields = JSON.parse(line);
+ const fields = JSON.parse(line);
result = Number(fields['__MONOTONIC_TIMESTAMP']);
}
datastream.close(null);
await Scripting.waitLeisure();
Scripting.scriptEvent('desktopShown');
- let interfaceSettings = new Gio.Settings({
+ const interfaceSettings = new Gio.Settings({
schema_id: 'org.gnome.desktop.interface',
});
interfaceSettings.set_boolean('enable-animations', false);
await Scripting.sleep(1000);
- let appSys = Shell.AppSystem.get_default();
- let app = appSys.lookup_app('org.gnome.gedit.desktop');
+ const appSys = Shell.AppSystem.get_default();
+ const app = appSys.lookup_app('org.gnome.gedit.desktop');
Scripting.scriptEvent('geditLaunch');
app.activate();
windows = app.get_windows();
}
- let actor = windows[0].get_compositor_private();
+ const actor = windows[0].get_compositor_private();
await waitSignal(actor, 'first-frame');
Scripting.scriptEvent('geditFirstFrame');
let applicationsShowStart;
let stagePaintStart;
let redrawTiming;
-let redrawTimes = {};
+const redrawTimes = {};
let geditLaunchTime;
/**
* @returns {void}
*/
export function script_desktopShown(time) {
- let bootTimestamp = extractBootTimestamp();
+ const bootTimestamp = extractBootTimestamp();
METRICS.timeToDesktop.value = time - bootTimestamp;
}
* @returns {void}
*/
export function script_collectTimings(_time) {
- for (let timing in redrawTimes) {
- let times = redrawTimes[timing];
+ for (const timing in redrawTimes) {
+ const times = redrawTimes[timing];
times.sort((a, b) => a - b);
- let len = times.length;
+ const len = times.length;
let median;
if (len === 0)
},
];
- for (let {name, input, output} of FindMatchingSlashParameters) {
+ for (const {name, input, output} of FindMatchingSlashParameters) {
it(`finds a matching slash where there are ${name}`, () => {
- let match = JsParse.findMatchingQuote(input, input.length - 1);
+ const match = JsParse.findMatchingQuote(input, input.length - 1);
expect(match).toEqual(output);
});
}
},
];
- for (let {name, input, output} of FindMatchingBraceParameters) {
+ for (const {name, input, output} of FindMatchingBraceParameters) {
it(`finds matching braces where there are ${name}`, () => {
- let match = JsParse.findMatchingBrace(input, input.length - 1);
+ const match = JsParse.findMatchingBrace(input, input.length - 1);
expect(match).toEqual(output);
});
}
for (const {name, input, output} of UnsafeExpressionParams) {
const isOrIsNot = output ? 'is' : 'is not';
it(`finds that an expression which is a ${name} ${isOrIsNot} safe`, () => {
- let unsafe = JsParse.isUnsafeExpression(input);
+ const unsafe = JsParse.isUnsafeExpression(input);
expect(unsafe).toEqual(output);
});
}